diff --git a/pm-stack/lane-guard/lane_guard.py b/pm-stack/lane-guard/lane_guard.py index f78aff8603..7522d4656f 100755 --- a/pm-stack/lane-guard/lane_guard.py +++ b/pm-stack/lane-guard/lane_guard.py @@ -11,7 +11,7 @@ re-posted the same park note on every 30-minute cycle (#7616 collected 50+ such notes in two days with no code). -Two checks, both pure functions over GitHub JSON so they are testable +Three checks, all pure functions over GitHub JSON so they are testable offline, plus a thin `gh` CLI wrapper for lanes to call: hold Is this issue/PR held for a human? Only an explicit marker @@ -36,14 +36,26 @@ the issue changes; re-posting it is the repeat-triage churn #12233 removes (#1062 collected four identical verdicts). -Usage (exit 0 = go ahead, 3 = held / skip the note, 2 = usage or I/O -error; JSON verdict on stdout either way): + coverage Is this issue covered by a recorded verdict (#12233 F2b, + decision record on the issue)? An open `effort/l` or + `effort/m` issue whose newest agent note is a triage + verdict with a recorded verdict token and a valid resume + condition (`resume=:` — a slice landed, a + dependency closed) is covered: the verdict note is the + park record for the triage disposition, so coverage must + not enqueue it for triage again. The verdict covers only + while it is the newest signal, under the same freshness + rule as the verdict dedupe above. + +Usage (exit 0 = go ahead, 3 = held / skip the note / covered, 2 = +usage or I/O error; JSON verdict on stdout either way): lane_guard.py hold --repo developing-today/code --issue 7616 lane_guard.py note --repo developing-today/code --issue 7616 \ --task 20028 --state parked lane_guard.py note --repo developing-today/code --issue 1062 \ --task 2334 --state triaged --verdict still_blocked + lane_guard.py coverage --repo developing-today/code --issue 1062 """ from __future__ import annotations @@ -72,6 +84,20 @@ # verdict, not by task or age: see note_verdict's verdict path. VERDICT_STATES = frozenset({"triaged"}) +# Effort classes a recorded verdict can cover (#12233 F2b, decision +# record on the issue): a verdict parks large and medium issues; small +# ones are meant to be picked up, not parked by a verdict. +COVERAGE_EFFORT_LABELS = frozenset({"effort/l", "effort/m"}) + +# Placeholder tokens that record no outcome: a note carrying one has +# not triaged anything, so it cannot cover the issue. +NON_VERDICTS = frozenset({"none", "unknown", "untriaged", "needs_triage"}) + +# Resume-condition kinds a verdict park may wait on (F2b decision +# record, rule 3): an event a later pass can check, never a date or a +# person. Recorded as `resume=:`. +RESUME_KINDS = frozenset({"slice_landed", "dependency_closed"}) + DEDUPE_WINDOW = timedelta(hours=24) EXIT_GO = 0 @@ -142,6 +168,30 @@ def hold_verdict(item: dict) -> dict: # `verdict=still_blocked` in the header area. A short token, so two # lanes recording the same outcome produce the same key. _VERDICT_RE = re.compile(r"\bverdict\s*[:=]\s*([A-Za-z0-9][\w -]*)", re.IGNORECASE) +# The resume condition of a verdict note: the `resume` field's value +# runs to the end of its line (or the header), and parse_resume picks +# the condition out of it. +_RESUME_FIELD_RE = re.compile(r"\bresume\s*[:=]\s*([^\n;]+)", re.IGNORECASE) +_RESUME_VALUE_RE = re.compile(r"([A-Za-z][A-Za-z_ -]*?)\s*(?::|#|\s)\s*#?(\d+)\b") + + +def parse_resume(raw) -> str | None: + """Canonical `kind:target` for a resume condition, or None when + the text is not one: the kind must be a checkable event + (RESUME_KINDS) and the target an issue/PR number. A date, a + person, or a kind with no target is not a resume condition — a + park nothing can check is a stall (F2b decision record, rule 3). + Accepts `dependency_closed:539`, `slice landed #12543`, and the + raw field value a note carries after `resume=`/`resume:`.""" + if not isinstance(raw, str): + return None + m = _RESUME_VALUE_RE.search(raw.strip()) + if not m: + return None + kind = _norm_verdict(m.group(1)) + if kind not in RESUME_KINDS: + return None + return f"{kind}:{m.group(2)}" # Lanes write notes free-form; these map the words they use to states. _STATE_WORDS = ( ( @@ -183,7 +233,10 @@ def parse_note(body: str) -> dict | None: (`**Pickup — queue task 20028**`). State is None when nothing recognisable is present; such a note never counts as a duplicate. A triage note that records a `verdict:`/`verdict=` field also - carries a normalised "verdict" key. + carries a normalised "verdict" key, and one that records a valid + `resume:`/`resume=` condition a canonical "resume" key + (`kind:target`, see parse_resume); an invalid resume condition is + not carried, so coverage can treat its absence as "no condition". """ if not isinstance(body, str) or not _MARKER.search(body): return None @@ -208,14 +261,26 @@ def parse_note(body: str) -> dict | None: verdict = _norm_verdict(m_verdict.group(1)) if verdict: note["verdict"] = verdict + m_resume = _RESUME_FIELD_RE.search(head) + if m_resume: + resume = parse_resume(m_resume.group(1)) + if resume: + note["resume"] = resume return note -def note_header(task: str, state: str, verdict: str | None = None) -> str: +def note_header( + task: str, state: str, verdict: str | None = None, resume: str | None = None +) -> str: """Canonical first line for a lane's agent note, so later dedupe checks parse it exactly. A triage note passes its verdict so the - next lane's check can match it.""" + next lane's check can match it, and its resume condition so + coverage (F2b) can read the park. The verdict stays last: its + free-form value runs to the end of the header, so a field after + it would be parsed as part of the verdict.""" header = f"" @@ -270,14 +335,19 @@ def _is_verdict_request(state, verdict) -> bool: return state in VERDICT_STATES or _norm_state(state) in VERDICT_STATES -def _verdict_note_verdict(comments, state, verdict, changes, now) -> dict: +def _verdict_note_verdict(comments, state, verdict, changes, now, resume=None) -> dict: """The verdict path of note_verdict (#12233 F2a): a triage verdict is skipped when the newest agent note already records the same verdict — for any task id, however long ago — and nothing has changed since: no human comment, and no commit, label or body change (from `changes`, see changes_from_timeline) after it. + A newly supplied resume condition still posts: when the stored + verdict note lacks the requested condition, or records a + different one, the note is the upgrade that gives the verdict + its F2b coverage, so dedupe must not swallow it. """ want = _verdict_key(state, verdict) + want_resume = parse_resume(resume) if resume else None for c in reversed(comments or []): note = parse_note(c.get("body")) if note is None: @@ -309,6 +379,16 @@ def _verdict_note_verdict(comments, state, verdict, changes, now) -> dict: f"change at {ch['at']}" ), } + if want_resume is not None and note.get("resume") != want_resume: + return { + "post": True, + "reason": ( + "resume condition added or changed: the newest verdict " + f"records {note.get('resume') or 'no resume condition'}, " + f"this note carries {want_resume}; post to record the " + "F2b resume condition" + ), + } age = now - since return { "post": False, @@ -324,7 +404,7 @@ def _verdict_note_verdict(comments, state, verdict, changes, now) -> dict: def note_verdict( - comments: list, task: str, state: str, now=None, verdict=None, changes=() + comments: list, task: str, state: str, now=None, verdict=None, changes=(), resume=None ) -> dict: """Should a note of `state` for queue `task` be posted, given the item's comments (oldest first, REST shape: body, created_at, @@ -332,14 +412,17 @@ def note_verdict( A triage verdict (state `triaged`, or any note with a `verdict`) takes the verdict path: `changes` is the issue's change list from - changes_from_timeline. Everything else takes the park path. + changes_from_timeline. `resume` is the resume condition the note + would record; a verdict that already stands still posts when the + condition adds or changes the stored one. Everything else takes + the park path. """ now = _ts(now) if now is not None else datetime.now(timezone.utc) state = str(state).lower().replace("-", "_") task = str(task).lstrip("#") verdict = _norm_verdict(verdict) if verdict else None if _is_verdict_request(state, verdict): - return _verdict_note_verdict(comments, state, verdict, changes, now) + return _verdict_note_verdict(comments, state, verdict, changes, now, resume) if state not in {s.replace("-", "_") for s in QUIET_STATES}: return {"post": True, "reason": f"progress state {state} always posts"} @@ -374,6 +457,111 @@ def note_verdict( return {"post": True, "reason": "no earlier agent note"} +# --- verdict coverage (#12233 F2b) --------------------------------------- + + +def coverage_verdict(item: dict, comments: list, changes=(), resume_fulfilled=None) -> dict: + """Is this issue covered by a recorded triage verdict? + + The F2b decision record on #12233: an open `effort/l` or + `effort/m` issue whose newest agent note is a triage verdict with + a recorded verdict token and a valid resume condition is covered + — the verdict note is the park record for the triage disposition, + so coverage must not enqueue the issue for triage again. The + verdict covers only while it is the newest signal, under the same + freshness rule as the F2a dedupe: a human comment, a newer agent + note of any other state, or a commit, label or body change after + the verdict (from `changes`, see changes_from_timeline) ends the + coverage. + + `resume_fulfilled`, when given, is a callable taking the + canonical resume condition (`kind:target`) and returning True + when the wait is over (the dependency closed, the slice landed), + False when its target is known not to be, or None when the + state cannot be read. A fulfilled condition ends coverage: the + issue is due for re-triage. An unreadable state never ends it. + + `item` is one issue JSON object (REST or `gh` shape), `comments` + its comments oldest first. Returns {"covered": bool, "reason": + str} plus "verdict" / "resume" when a verdict note was found. + """ + state = str(item.get("state") or "").lower() + if state and state != "open": + return {"covered": False, "reason": f"issue is not open ({state})"} + labels = set(_names(item.get("labels"), "name")) + if not labels & COVERAGE_EFFORT_LABELS: + return { + "covered": False, + "reason": "no effort/l or effort/m label: a verdict parks " + "only large or medium issues", + } + for c in reversed(comments or []): + note = parse_note(c.get("body")) + if note is None: + user = c.get("user") or {} + if user.get("type") == "Bot": + continue # bots (CI, sweepers) are not news + return { + "covered": False, + "reason": "a non-agent comment arrived since the last agent note", + } + if note["state"] not in VERDICT_STATES or not note.get("verdict"): + return { + "covered": False, + "reason": "newest agent note is not a recorded triage " + f"verdict (it was {note['state']})", + } + verdict = note["verdict"] + if verdict in NON_VERDICTS: + return { + "covered": False, + "verdict": verdict, + "reason": f"recorded verdict {verdict} records no outcome", + } + if not note.get("resume"): + return { + "covered": False, + "verdict": verdict, + "reason": "the verdict note carries no valid resume " + "condition (resume=:" + ")", + } + if resume_fulfilled is not None: + try: + fulfilled = resume_fulfilled(note["resume"]) + except Exception: + fulfilled = None # unreadable: the wait is not over + if fulfilled: + return { + "covered": False, + "verdict": verdict, + "resume": note["resume"], + "reason": "the resume condition " + f"{note['resume']} is fulfilled; the issue is " + "due for re-triage", + } + since = _ts(c.get("created_at")) + for ch in changes or (): + if _ts(ch["at"]) > since: + return { + "covered": False, + "verdict": verdict, + "resume": note["resume"], + "reason": "the issue changed since the verdict: a " + f"{ch['kind']} change at {ch['at']}", + } + return { + "covered": True, + "verdict": verdict, + "resume": note["resume"], + "reason": f"verdict-covered: verdict {verdict} recorded for " + f"task {note['task']} with resume condition {note['resume']}; " + "the verdict note is the park record — do not re-enqueue " + "for triage", + } + return {"covered": False, "reason": "no earlier agent note"} + + # --- thin gh wrapper ---------------------------------------------------- @@ -411,6 +599,19 @@ def main(argv=None, gh=_gh_json, now=None) -> int: "an unchanged issue with the same verdict already recorded " "skips the note", ) + n.add_argument( + "--resume", + default=None, + help="the resume condition this verdict parks on (state " + "triaged): slice_landed: or dependency_closed:; " + "a verdict note with a valid condition covers the issue " + "for coverage (F2b)", + ) + c = sub.add_parser( + "coverage", help="is this issue covered by a recorded verdict?" + ) + c.add_argument("--repo", required=True) + c.add_argument("--issue", required=True, type=int) args = ap.parse_args(argv) try: @@ -418,6 +619,37 @@ def main(argv=None, gh=_gh_json, now=None) -> int: item = gh(f"repos/{args.repo}/issues/{args.issue}") verdict = hold_verdict(item) code = EXIT_STOP if verdict["held"] else EXIT_GO + elif args.cmd == "coverage": + item = gh(f"repos/{args.repo}/issues/{args.issue}") + comments = gh( + f"repos/{args.repo}/issues/{args.issue}/comments?per_page=100" + ) + timeline = gh( + f"repos/{args.repo}/issues/{args.issue}/timeline?per_page=100" + ) + + # The verdict's wait is over when its resume target reads + # fulfilled live: a closed dependency, a merged slice (a + # PR closed without merging did not land it). An + # unreadable target is unknown, never fulfilled. + def _resume_fulfilled(resume): + try: + kind, _, target = resume.partition(":") + if kind == "dependency_closed": + target_item = gh(f"repos/{args.repo}/issues/{target}") + return (target_item or {}).get("state") == "closed" + target_pr = gh(f"repos/{args.repo}/pulls/{target}") + return bool((target_pr or {}).get("merged_at")) + except Exception: + return None + + verdict = coverage_verdict( + item, + comments, + changes=changes_from_timeline(timeline), + resume_fulfilled=_resume_fulfilled, + ) + code = EXIT_STOP if verdict["covered"] else EXIT_GO else: comments = gh( f"repos/{args.repo}/issues/{args.issue}/comments?per_page=100" @@ -434,10 +666,11 @@ def main(argv=None, gh=_gh_json, now=None) -> int: args.state, now=now, verdict=args.verdict, + resume=args.resume, changes=changes, ) verdict["header"] = note_header( - args.task, args.state, verdict=args.verdict + args.task, args.state, verdict=args.verdict, resume=args.resume ) code = EXIT_GO if verdict["post"] else EXIT_STOP except ( diff --git a/pm-stack/lane-guard/test_lane_guard.py b/pm-stack/lane-guard/test_lane_guard.py index 7d94188bad..cbcfba18db 100644 --- a/pm-stack/lane-guard/test_lane_guard.py +++ b/pm-stack/lane-guard/test_lane_guard.py @@ -71,6 +71,15 @@ def comment(body, minutes_ago, user_type="User"): "Verdict: still blocked on F12.4 (#1061)." ) TRIAGED_NO_VERDICT = "agent-note:v1\nstate: triaged\ntask: 22222\n\nStill live." +# Verdict notes carrying the F2b resume condition, in both shapes. +HTML_TRIAGED_RESUME = ( + "\nTriaged: still blocked on F11.8 (#539)." +) +YAML_TRIAGED_RESUME = ( + "agent-note:v1\nstate: triaged\ntask: 22222\nverdict: still_blocked\n" + "resume: slice landed #12543\n\nVerdict: still blocked; the F2a slice lands first." +) def at(minutes_ago): @@ -186,6 +195,42 @@ def test_canonical_header_with_verdict_round_trips(self): {"state": "triaged", "task": "20028", "verdict": "still_blocked"}, ) + def test_resume_field_is_parsed_and_canonicalised(self): + for body in (HTML_TRIAGED_RESUME, YAML_TRIAGED_RESUME): + with self.subTest(body=body[:30]): + note = lg.parse_note(body) + self.assertEqual(note["state"], "triaged") + self.assertEqual(note["verdict"], "still_blocked") + self.assertIn(note["resume"], ("dependency_closed:539", "slice_landed:12543")) + + def test_canonical_header_with_resume_round_trips(self): + self.assertEqual( + lg.parse_note( + lg.note_header( + "20028", + "triaged", + verdict="still_blocked", + resume="dependency closed #539", + ) + + "\nTriaged." + ), + { + "state": "triaged", + "task": "20028", + "verdict": "still_blocked", + "resume": "dependency_closed:539", + }, + ) + + def test_parse_resume_rejects_dates_people_and_bare_kinds(self): + for raw in ("next week", "2027-01-01", "the owner", "slice_landed", "dependency_closed:"): + with self.subTest(raw=raw): + self.assertIsNone(lg.parse_resume(raw)) + self.assertEqual(lg.parse_resume("slice_landed:12543"), "slice_landed:12543") + self.assertEqual( + lg.parse_resume("dependency closed #539"), "dependency_closed:539" + ) + def test_plain_comment_is_not_a_note(self): self.assertIsNone(lg.parse_note("Looks good, ship it.")) self.assertIsNone(lg.parse_note(None)) @@ -265,9 +310,10 @@ class VerdictNote(unittest.TestCase): """#12233 F2a: a triage verdict is posted once per verdict per unchanged issue, across task ids.""" - def verdict(self, cs, task="99999", verdict="still_blocked", changes=()): + def verdict(self, cs, task="99999", verdict="still_blocked", changes=(), resume=None): return lg.note_verdict( - cs, task, "triaged", now=NOW, verdict=verdict, changes=changes + cs, task, "triaged", now=NOW, verdict=verdict, changes=changes, + resume=resume, ) def test_same_verdict_other_task_unchanged_issue_is_skipped(self): @@ -342,10 +388,161 @@ def test_recorded_verdict_does_not_match_unrecorded(self): ) self.assertTrue(v["post"]) + def test_new_resume_condition_posts_despite_duplicate_verdict(self): + # Thread 4 (P2, #12565): the stored verdict has no resume + # condition; the same verdict WITH one still posts, so the + # caller can upgrade it to F2b coverage. + v = self.verdict( + [comment(HTML_TRIAGED, 40)], resume="dependency_closed:539" + ) + self.assertTrue(v["post"]) + self.assertIn("resume condition", v["reason"]) + + def test_same_resume_condition_still_skips(self): + v = self.verdict( + [comment(HTML_TRIAGED_RESUME, 40)], resume="dependency_closed:539" + ) + self.assertFalse(v["post"]) + + def test_changed_resume_condition_posts(self): + v = self.verdict( + [comment(HTML_TRIAGED_RESUME, 40)], resume="slice_landed:12543" + ) + self.assertTrue(v["post"]) + self.assertIn("resume condition", v["reason"]) + + def test_invalid_resume_condition_still_skips(self): + # A resume value that is not a checkable condition is not a + # reason to re-post. + v = self.verdict([comment(HTML_TRIAGED, 40)], resume="next week") + self.assertFalse(v["post"]) + def test_first_verdict_posts(self): self.assertTrue(self.verdict([])["post"]) +class CoverageVerdict(unittest.TestCase): + """#12233 F2b: coverage accepts a verdict — an open effort/l or + effort/m issue whose newest agent note is a recorded triage + verdict with a valid resume condition is covered, and an issue + with no verdict is still uncovered.""" + + def coverage(self, cs, labels=("effort/l",), changes=(), state="open", + resume_fulfilled=None): + return lg.coverage_verdict( + issue(list(labels), state=state), cs, changes=changes, + resume_fulfilled=resume_fulfilled, + ) + + def test_verdict_with_resume_covers_large_and_medium(self): + for body in (HTML_TRIAGED_RESUME, YAML_TRIAGED_RESUME): + for labels in (("effort/l",), ("effort/m",)): + with self.subTest(body=body[:30], labels=labels): + v = self.coverage([comment(body, 40)], labels=labels) + self.assertTrue(v["covered"]) + self.assertEqual(v["verdict"], "still_blocked") + self.assertIn("resume condition", v["reason"]) + + def test_no_verdict_is_not_covered(self): + self.assertFalse(self.coverage([])["covered"]) + v = self.coverage([comment(YAML_PARKED, 10)]) + self.assertFalse(v["covered"]) + self.assertIn("not a recorded triage verdict", v["reason"]) + + def test_state_only_verdict_is_not_covered(self): + # Coverage reads the recorded token (decision record rule 1); + # a state-only note has none. + v = self.coverage([comment(TRIAGED_NO_VERDICT, 40)]) + self.assertFalse(v["covered"]) + + def test_verdict_without_resume_is_not_covered(self): + v = self.coverage([comment(HTML_TRIAGED, 40)]) + self.assertFalse(v["covered"]) + self.assertIn("no valid resume condition", v["reason"]) + + def test_placeholder_verdict_is_not_covered(self): + body = ( + "\nTriaged." + ) + v = self.coverage([comment(body, 40)]) + self.assertFalse(v["covered"]) + self.assertIn("records no outcome", v["reason"]) + + def test_small_or_unlabelled_issue_is_not_covered(self): + for labels in (("effort/s",), ()): + with self.subTest(labels=labels): + v = self.coverage([comment(HTML_TRIAGED_RESUME, 40)], labels=labels) + self.assertFalse(v["covered"]) + self.assertIn("effort/l or effort/m", v["reason"]) + + def test_closed_issue_is_not_covered(self): + v = self.coverage([comment(HTML_TRIAGED_RESUME, 40)], state="closed") + self.assertFalse(v["covered"]) + self.assertIn("not open", v["reason"]) + + def test_human_comment_after_verdict_ends_coverage(self): + cs = [comment(HTML_TRIAGED_RESUME, 40), comment("Drew: reopen this.", 10)] + self.assertFalse(self.coverage(cs)["covered"]) + + def test_bot_comment_after_verdict_keeps_coverage(self): + cs = [ + comment(HTML_TRIAGED_RESUME, 40), + comment("CI summary", 10, user_type="Bot"), + ] + self.assertTrue(self.coverage(cs)["covered"]) + + def test_newer_progress_note_ends_coverage(self): + cs = [comment(HTML_TRIAGED_RESUME, 40), comment(PR_OPENED, 10)] + self.assertFalse(self.coverage(cs)["covered"]) + + def test_issue_change_after_verdict_ends_coverage(self): + changes = [{"kind": "commit", "at": at(10)}] + v = self.coverage([comment(HTML_TRIAGED_RESUME, 40)], changes=changes) + self.assertFalse(v["covered"]) + self.assertIn("commit", v["reason"]) + + def test_change_before_the_verdict_keeps_coverage(self): + changes = [{"kind": "label", "at": at(50)}] + v = self.coverage([comment(HTML_TRIAGED_RESUME, 40)], changes=changes) + self.assertTrue(v["covered"]) + + def test_fulfilled_resume_condition_ends_coverage(self): + # Thread 1 (P1, #12565): the dependency closed, so the + # verdict's wait is over and the issue is due for re-triage. + seen = [] + v = self.coverage( + [comment(HTML_TRIAGED_RESUME, 40)], + resume_fulfilled=lambda r: seen.append(r) or True, + ) + self.assertFalse(v["covered"]) + self.assertIn("fulfilled", v["reason"]) + self.assertEqual(seen, ["dependency_closed:539"]) + + def test_unfulfilled_resume_condition_keeps_coverage(self): + v = self.coverage( + [comment(HTML_TRIAGED_RESUME, 40)], + resume_fulfilled=lambda r: False, + ) + self.assertTrue(v["covered"]) + + def test_unknown_resume_state_keeps_coverage(self): + v = self.coverage( + [comment(HTML_TRIAGED_RESUME, 40)], + resume_fulfilled=lambda r: None, + ) + self.assertTrue(v["covered"]) + + def test_resume_checker_error_keeps_coverage(self): + def boom(r): + raise RuntimeError("gh down") + + v = self.coverage( + [comment(HTML_TRIAGED_RESUME, 40)], resume_fulfilled=boom + ) + self.assertTrue(v["covered"]) + + class ChangesFromTimeline(unittest.TestCase): def test_maps_change_events(self): events = [ @@ -488,6 +685,92 @@ def gh(path): self.assertTrue(out["post"]) self.assertIn("commit", out["reason"]) + def test_coverage_cli_covered_is_stop(self): + seen = [] + + def gh(path): + seen.append(path) + if "timeline" in path: + return [] + if "comments" in path: + return [comment(HTML_TRIAGED_RESUME, 5)] + return issue(["effort/l"]) + + code, out = self.run_cli( + ["coverage", "--repo", "o/r", "--issue", "1062"], gh=gh + ) + self.assertEqual( + seen, + [ + "repos/o/r/issues/1062", + "repos/o/r/issues/1062/comments?per_page=100", + "repos/o/r/issues/1062/timeline?per_page=100", + # The resume target is read live: dependency 539 is + # open here, so the wait is not over. + "repos/o/r/issues/539", + ], + ) + self.assertEqual(code, lg.EXIT_STOP) + self.assertTrue(out["covered"]) + self.assertEqual(out["resume"], "dependency_closed:539") + + def test_coverage_cli_fulfilled_resume_is_go(self): + def gh(path): + if "timeline" in path: + return [] + if "comments" in path: + return [comment(HTML_TRIAGED_RESUME, 5)] + if path.endswith("/issues/539"): + return {"state": "closed"} + return issue(["effort/l"]) + + code, out = self.run_cli( + ["coverage", "--repo", "o/r", "--issue", "1062"], gh=gh + ) + self.assertEqual(code, lg.EXIT_GO) + self.assertFalse(out["covered"]) + self.assertIn("fulfilled", out["reason"]) + + def test_coverage_cli_uncovered_is_go(self): + def gh(path): + if "timeline" in path: + return [] + if "comments" in path: + return [comment(HTML_TRIAGED_RESUME, 5)] + return issue(["effort/s"]) + + code, out = self.run_cli( + ["coverage", "--repo", "o/r", "--issue", "1062"], gh=gh + ) + self.assertEqual(code, lg.EXIT_GO) + self.assertFalse(out["covered"]) + + def test_note_cli_with_resume_writes_it_into_the_header(self): + code, out = self.run_cli( + [ + "note", + "--repo", + "o/r", + "--issue", + "1062", + "--task", + "20028", + "--state", + "triaged", + "--verdict", + "still_blocked", + "--resume", + "dependency_closed:539", + ], + gh=lambda path: [], + ) + self.assertEqual(code, lg.EXIT_GO) + self.assertEqual( + out["header"], + "", + ) + def test_gh_failure_is_exit_2(self): def boom(path): raise RuntimeError("HTTP 502") diff --git a/scripts/fleet/queue-reconcile/README.md b/scripts/fleet/queue-reconcile/README.md index 1c0f5a9ba2..259038d203 100644 --- a/scripts/fleet/queue-reconcile/README.md +++ b/scripts/fleet/queue-reconcile/README.md @@ -44,6 +44,17 @@ one merge-watch packet per PR (dedupe re-tests mergibility, refreshes the branch, merges, or closes the PR with a salvage note, instead of letting pr_opened work bit-rot. +**Verdict coverage (#12233 F2b):** the broker diff only knows tasks, +so `check_coverage.py` also reads the recorded verdict on an +`effort/l` or `effort/m` issue it would otherwise call uncovered. +When the issue's newest agent note is a triage verdict with a +recorded verdict token and a valid resume condition +(`resume=:`), the verdict +note is the park record for the triage disposition: the issue is +covered and gets no new triage packet. The decision record with the +full rules is on #12233; `pm-stack/lane-guard/lane_guard.py +coverage` applies the same rules to a single issue. + ## Running it ```bash diff --git a/scripts/fleet/queue-reconcile/check_coverage.py b/scripts/fleet/queue-reconcile/check_coverage.py index 5f7dae14e4..c1262f60d3 100644 --- a/scripts/fleet/queue-reconcile/check_coverage.py +++ b/scripts/fleet/queue-reconcile/check_coverage.py @@ -48,6 +48,27 @@ refresh the branch, merge, or close with a salvage note. Fixtures carry the PR set under a top-level `"pulls": {"owner/repo": [...]}`. +Verdict coverage (#12233 F2b, decision record on the issue): an open +`effort/l` or `effort/m` issue whose newest agent note records a +triage verdict with a valid resume condition +(`resume=:`) is parked by +that verdict — the note is the park record for the triage +disposition — so the broker calling it uncovered does not get it +re-enqueued for triage. The lane-guard `coverage` check +(`pm-stack/lane-guard/lane_guard.py`) applies the same rules to a +single issue. Fixtures carry the fields on the issue objects: +`labels`, `verdict`, `resume_condition`. In live mode the labels +come with the enumeration and the verdict is read from the issue's +comments, for broker-uncovered effort issues only. + +The coverage is released when the verdict stops parking the issue: +the resume condition is evaluated against live state (a closed +dependency, a merged slice), and a label, commit or body change +after the verdict ends it — the same freshness rule the lane +guard applies. A verdict that cannot be read (a failed comments +fetch) is never treated as absent: the issue is skipped from the +import, reported as an error, and the run exits 3. + Exit codes: 0 = run completed (uncovered may be > 0 in observe mode), 2 = configuration/usage error, 3 = a fetch or broker call failed (the report names which; a failure never masquerades as "0 uncovered"). @@ -111,7 +132,8 @@ def fetch_open_issues(repo: str, gh: str = "gh") -> list[dict]: "--paginate", f"repos/{repo}/issues?state=open&per_page=100", "--jq", - '.[] | select(has("pull_request") | not) | {number, title}', + '.[] | select(has("pull_request") | not) | ' + "{number, title, labels: [.labels[].name]}", ] try: out = subprocess.run(cmd, capture_output=True, text=True, timeout=180) @@ -206,6 +228,373 @@ def build_pr_coverage(prs: list[dict]) -> dict[int, dict]: return coverage +# --------------------------------------------------------------------------- +# Verdict coverage (#12233 F2b): a recorded verdict parks a large issue +# --------------------------------------------------------------------------- + +# The rules in this section are the F2b decision record on #12233 and +# are kept in step with pm-stack/lane-guard/lane_guard.py, whose +# `coverage` check applies them to a single issue: an open effort/l +# or effort/m issue whose newest agent note is a triage verdict with +# a recorded verdict token and a valid resume condition is covered. +VERDICT_EFFORT_LABELS = frozenset({"effort/l", "effort/m"}) +RESUME_KINDS = frozenset({"slice_landed", "dependency_closed"}) +NON_VERDICTS = frozenset({"none", "unknown", "untriaged", "needs_triage"}) + +_RESUME_VALUE_RE = re.compile(r"([A-Za-z][A-Za-z_ -]*?)\s*(?::|#|\s)\s*#?(\d+)\b") +_AGENT_NOTE_MARKER = re.compile(r"agent-note[:-]v1|\*\*Agent note\*\*", re.IGNORECASE) +_NOTE_STATE_RE = re.compile(r"\bstate\s*[:=]\s*([A-Za-z_-]+)", re.IGNORECASE) +_NOTE_VERDICT_RE = re.compile(r"\bverdict\s*[:=]\s*([A-Za-z0-9][\w -]*)", re.IGNORECASE) +_NOTE_RESUME_RE = re.compile(r"\bresume\s*[:=]\s*([^\n;]+)", re.IGNORECASE) + + +def _issue_label_names(issue: dict) -> list[str]: + names: list[str] = [] + for lab in issue.get("labels") or []: + if isinstance(lab, dict): + lab = lab.get("name") + if isinstance(lab, str) and lab: + names.append(lab) + return names + + +def _norm_token(raw: str) -> str: + return re.sub(r"[^a-z0-9]+", "_", str(raw).lower()).strip("_") + + +def parse_resume_condition(value) -> str | None: + """Canonical `kind:target` for a resume condition, or None. + + Accepts the string forms a note or fixture carries + (`dependency_closed:539`, `slice landed #12543`) and the dict + form (`{"kind": ..., "target": ...}`). The kind must be a + checkable event and the target an issue/PR number: a date, a + person, or a kind with no target is not a resume condition. + """ + if isinstance(value, dict): + kind = _norm_token(value.get("kind") or "") + target = str(value.get("target") or "").lstrip("#") + if kind in RESUME_KINDS and target.isdigit(): + return f"{kind}:{target}" + return None + if not isinstance(value, str): + return None + m = _RESUME_VALUE_RE.search(value.strip()) + if not m: + return None + kind = _norm_token(m.group(1)) + if kind not in RESUME_KINDS: + return None + return f"{kind}:{m.group(2)}" + + +def verdict_coverage(issue: dict) -> dict | None: + """{"verdict", "resume"} when the issue's recorded verdict parks + it under F2b, else None. The issue dict carries `labels`, + `verdict` and `resume_condition` (fixture fields, or the live + enrichment from fetch_issue_verdict).""" + if not (set(_issue_label_names(issue)) & VERDICT_EFFORT_LABELS): + return None + verdict = _norm_token(issue.get("verdict") or "") + if not verdict or verdict in NON_VERDICTS: + return None + resume = parse_resume_condition( + issue.get("resume_condition") or issue.get("resume") + ) + if not resume: + return None + return {"verdict": verdict, "resume": resume} + + +def verdict_from_comments(comments: list) -> dict: + """{"verdict", "resume_condition"} read from the newest agent + note, or {} when that note is not a recorded triage verdict. + + Mirrors the lane-guard freshness rule: the scan stops at the + newest non-bot comment — a human comment or a newer agent note + of any other state means the verdict is no longer the newest + signal, so it does not cover. + """ + for c in reversed(comments or []): + body = c.get("body") or "" + if not _AGENT_NOTE_MARKER.search(body): + user = c.get("user") or {} + if user.get("type") == "Bot": + continue # bots (CI, sweepers) are not news + return {} + head = body[:600] + m_state = _NOTE_STATE_RE.search(head) + m_verdict = _NOTE_VERDICT_RE.search(head) + if ( + not m_state + or m_state.group(1).lower().replace("-", "_") != "triaged" + or not m_verdict + ): + return {} + out = {"verdict": _norm_token(m_verdict.group(1))} + m_resume = _NOTE_RESUME_RE.search(head) + if m_resume: + resume = parse_resume_condition(m_resume.group(1)) + if resume: + out["resume_condition"] = resume + return out + return {} + + +def verdict_from_comments(comments: list) -> dict: + """{"verdict", "resume_condition"} read from the newest agent + note, or {} when that note is not a recorded triage verdict. + + Mirrors the lane-guard freshness rule: the scan stops at the + newest non-bot comment — a human comment or a newer agent note + of any other state means the verdict is no longer the newest + signal, so it does not cover. When the note comment carries a + timestamp it is returned as `verdict_at`, so the caller can + check the timeline for changes after the verdict. + """ + for c in reversed(comments or []): + body = c.get("body") or "" + if not _AGENT_NOTE_MARKER.search(body): + user = c.get("user") or {} + if user.get("type") == "Bot": + continue # bots (CI, sweepers) are not news + return {} + head = body[:600] + m_state = _NOTE_STATE_RE.search(head) + m_verdict = _NOTE_VERDICT_RE.search(head) + if ( + not m_state + or m_state.group(1).lower().replace("-", "_") != "triaged" + or not m_verdict + ): + return {} + out = {"verdict": _norm_token(m_verdict.group(1))} + m_resume = _NOTE_RESUME_RE.search(head) + if m_resume: + resume = parse_resume_condition(m_resume.group(1)) + if resume: + out["resume_condition"] = resume + if c.get("created_at"): + out["verdict_at"] = c["created_at"] + return out + return {} + + +def _parse_ts(value) -> datetime | None: + """An ISO-8601 timestamp, or None when it cannot be read.""" + try: + return datetime.fromisoformat(str(value).replace("Z", "+00:00")) + except (ValueError, TypeError): + return None + + +# Timeline event -> the kind of issue change it proves, kept in step +# with lane_guard.changes_from_timeline: a commit referenced on the +# issue, a label change, a body edit. `commented` is deliberately +# absent: comments are judged from the comment list itself, where +# human vs bot is visible. +_TIMELINE_CHANGES = {"labeled": "label", "unlabeled": "label", "edited": "body"} + + +def changes_from_timeline(events: list) -> list: + """[{"kind", "at"}] for the issue changes a verdict must not + outlive. A `referenced` event only counts as a commit when it + carries a commit_id (a cross-reference from another issue is + not one).""" + out = [] + for e in events or []: + if not isinstance(e, dict): + continue + kind = _TIMELINE_CHANGES.get(e.get("event")) + if e.get("event") == "referenced" and e.get("commit_id"): + kind = "commit" + if kind and e.get("created_at"): + out.append({"kind": kind, "at": e["created_at"]}) + return out + + +def verdict_fresh(issue: dict) -> bool: + """True unless a recorded timeline change postdates the verdict. + + The issue carries `verdict_at` (the verdict note's timestamp) + and `timeline_changes` (from fetch_issue_verdict, or a fixture). + With neither recorded there is nothing to compare, so the + verdict stands; an unreadable timestamp never invents staleness. + """ + verdict_at = _parse_ts(issue.get("verdict_at")) + if verdict_at is None: + return True + for ch in issue.get("timeline_changes") or []: + at = _parse_ts(ch.get("at") if isinstance(ch, dict) else None) + if at is not None and at > verdict_at: + return False + return True + + +def fetch_issue_timeline(repo: str, number: int, gh: str = "gh") -> list: + """The issue changes a verdict must not outlive, from the + issue timeline. A failed fetch is a FetchError: without the + timeline the verdict's freshness is unknown, so the caller + must not treat the verdict as fresh.""" + cmd = [ + gh, + "api", + "--paginate", + f"repos/{repo}/issues/{number}/timeline?per_page=100", + "--jq", + ".[] | {event, created_at, commit_id}", + ] + try: + out = subprocess.run(cmd, capture_output=True, text=True, timeout=180) + except (OSError, subprocess.TimeoutExpired) as exc: + raise FetchError(f"github timeline failed for {repo}#{number}: {exc}") from exc + if out.returncode != 0: + raise FetchError( + f"github timeline failed for {repo}#{number} (exit {out.returncode}): " + f"{out.stderr.strip()[:400]}" + ) + events: list[dict] = [] + for line in out.stdout.splitlines(): + line = line.strip() + if line: + events.append(json.loads(line)) + return changes_from_timeline(events) + + +def fetch_issue_verdict(repo: str, number: int, gh: str = "gh") -> dict: + """The recorded verdict on one issue, from its comments. + + A failed fetch is a FetchError, exactly like the enumerations: + an unread issue must never read as verdict-covered (which would + suppress triage) or silently as verdict-free. When a verdict is + found, its timeline is fetched too and returned as + `timeline_changes`, so the caller can end coverage on a label, + commit or body change after the verdict (verdict_fresh). + """ + cmd = [ + gh, + "api", + "--paginate", + f"repos/{repo}/issues/{number}/comments?per_page=100", + "--jq", + '.[] | {body, created_at, user: {type: .user.type}}', + ] + try: + out = subprocess.run(cmd, capture_output=True, text=True, timeout=180) + except (OSError, subprocess.TimeoutExpired) as exc: + raise FetchError(f"github comments failed for {repo}#{number}: {exc}") from exc + if out.returncode != 0: + raise FetchError( + f"github comments failed for {repo}#{number} (exit {out.returncode}): " + f"{out.stderr.strip()[:400]}" + ) + comments: list[dict] = [] + for line in out.stdout.splitlines(): + line = line.strip() + if line: + comments.append(json.loads(line)) + verdict = verdict_from_comments(comments) + if verdict: + verdict["timeline_changes"] = fetch_issue_timeline(repo, number, gh) + return verdict + + +# --------------------------------------------------------------------------- +# Resume conditions (#12233 F2b): is the verdict's wait over? +# --------------------------------------------------------------------------- +# +# Decision (FDR-0013: decide, record, continue — no owner gate): a +# resume condition is fulfilled by live GitHub state, checked at +# reconciliation time. `dependency_closed:N` is fulfilled iff issue +# N is closed. `slice_landed:N` is fulfilled iff PR N is merged; a +# PR closed without merging did not land the slice, so it does not +# release the verdict. A target whose state cannot be read is +# unknown, never fulfilled: the issue stays covered and the failure +# is reported (exit 3), so a transient outage cannot re-triage a +# parked issue or park one whose wait is over. + + +def resume_fulfilled(resume: str, state: str | None) -> bool | None: + """True/False when `state` settles the resume condition, None + when the state is unknown or unrecognised.""" + kind, _, _ = resume.partition(":") + if kind == "dependency_closed": + if state == "closed": + return True + if state == "open": + return False + return None + if kind == "slice_landed": + if state == "merged": + return True + if state in ("open", "closed"): + return False + return None + return None + + +def fetch_resume_state(repo: str, resume: str, gh: str = "gh") -> str: + """The live state of a resume condition's target: an issue's + state, or a PR's state with "merged" when it has a merge + timestamp. A failed fetch is a FetchError.""" + kind, _, target = resume.partition(":") + if kind == "dependency_closed": + cmd = [gh, "api", f"repos/{repo}/issues/{target}", "--jq", ".state"] + elif kind == "slice_landed": + cmd = [ + gh, + "api", + f"repos/{repo}/pulls/{target}", + "--jq", + "{merged: (.merged_at != null), state: .state}", + ] + else: + raise FetchError(f"unknown resume kind in {resume!r}") + try: + out = subprocess.run(cmd, capture_output=True, text=True, timeout=180) + except (OSError, subprocess.TimeoutExpired) as exc: + raise FetchError( + f"github resume target failed for {repo} {resume}: {exc}" + ) from exc + if out.returncode != 0: + raise FetchError( + f"github resume target failed for {repo} {resume} " + f"(exit {out.returncode}): {out.stderr.strip()[:400]}" + ) + if kind == "dependency_closed": + # `--jq .state` emits the raw state word (`closed` / `open`), + # not JSON — read it as stripped text. Decoding it as JSON + # raised on every live lookup and left closed dependencies + # classified unknown. + return out.stdout.strip() + try: + value = json.loads(out.stdout.strip()) + except json.JSONDecodeError as exc: + raise FetchError( + f"github resume target failed for {repo} {resume}: unreadable reply" + ) from exc + if kind == "slice_landed": + return "merged" if value.get("merged") else str(value.get("state") or "") + return str(value or "") + + +def resolve_resume( + repo: str, resume: str, states: dict | None = None, gh: str = "gh" +) -> bool | None: + """True when the resume condition is fulfilled, False when its + target is known not to be, None when fulfilment is unknown. + `states` is the fixture-mode map of canonical resume condition + to target state (`"closed"` / `"open"` for a dependency, + `"merged"` / `"open"` / `"closed"` for a slice); with no map the + target is read live. A resume condition absent from the map is + unknown, never assumed fulfilled.""" + if states is not None: + if resume not in states: + return None + return resume_fulfilled(resume, states[resume]) + return resume_fulfilled(resume, fetch_resume_state(repo, resume, gh)) + + # --------------------------------------------------------------------------- # Broker: the coverage diff # --------------------------------------------------------------------------- @@ -455,29 +844,79 @@ def render_report( f"# Queue coverage reconciliation — {checked_at}", "", f"Mode: **{mode}**. Doctrine: every open issue must hold a LIVE task " - "(queued/claimed/parked/blocked) in its own pilot queue; a done task is not coverage.", + "(queued/claimed/parked/blocked) in its own pilot queue; a done task is not coverage, " + "but a recorded verdict with a resume condition is parked coverage (#12233 F2b).", "", - "| repo | queue | open issues | covered | open-PR covered | uncovered | imported | watch imported |", - "|---|---|---|---|---|---|---|---|", + "| repo | queue | open issues | covered | open-PR covered | verdict covered | uncovered | imported | watch imported |", + "|---|---|---|---|---|---|---|---|---|", ] for r in results: lines.append( f"| {r['repo']} | {r['queue']} | {r['open_issues']} | {r['covered']} " - f"| {r.get('pr_covered', 0)} | {r['uncovered']} | {r['imported']} " + f"| {r.get('pr_covered', 0)} | {r.get('verdict_covered', 0)} " + f"| {r['uncovered']} | {r['imported']} " f"| {r.get('watch_imported', 0)} |" ) total_uncovered = sum(r["uncovered"] for r in results) total_imported = sum(r["imported"] for r in results) total_pr = sum(r.get("pr_covered", 0) for r in results) + total_verdict = sum(r.get("verdict_covered", 0) for r in results) total_watch = sum(r.get("watch_imported", 0) for r in results) + total_unread = sum(len(r.get("verdict_unread_issues", [])) for r in results) + total_fulfilled = sum( + len(r.get("resume_fulfilled_issues", [])) for r in results + ) + total_stale = sum(len(r.get("stale_issues", [])) for r in results) lines += [ "", f"**Total uncovered: {total_uncovered}** · imported this run: {total_imported}", f"Open-PR covered (#4951): {total_pr} · merge-watch imported this run: {total_watch}", + f"Verdict covered (#12233 F2b): {total_verdict}", + f"Verdict unread (fetch failed — skipped from import): {total_unread} " + f"· resume condition fulfilled (due for re-triage): {total_fulfilled} " + f"· verdict stale (changed after the verdict): {total_stale}", "", ] if errors: lines += ["## ERRORS", ""] + [f"- {e}" for e in errors] + [""] + unread_any = [(r, i) for r in results for i in r.get("verdict_unread_issues", [])] + if unread_any: + lines += [ + "## Verdict unread — fetch failed, skipped from import (#12233 F2b)", + "", + ] + for r, i in unread_any: + lines.append( + f"- {r['repo']}#{i['number']} — the recorded verdict could not be " + "read, so no triage packet was enqueued for it" + ) + lines.append("") + fulfilled_any = [ + (r, i) for r in results for i in r.get("resume_fulfilled_issues", []) + ] + if fulfilled_any: + lines += [ + "## Resume condition fulfilled — due for re-triage (#12233 F2b)", + "", + ] + for r, i in fulfilled_any: + lines.append( + f"- {r['repo']}#{i['number']} — verdict {i.get('verdict')} " + f"(resume {i.get('resume')} fulfilled)" + ) + lines.append("") + stale_any = [(r, i) for r in results for i in r.get("stale_issues", [])] + if stale_any: + lines += [ + "## Verdict stale — issue changed after the verdict (#12233 F2b)", + "", + ] + for r, i in stale_any: + lines.append( + f"- {r['repo']}#{i['number']} — verdict {i.get('verdict')} " + "(a label, commit or body change postdates the verdict)" + ) + lines.append("") pr_any = [(r, i) for r in results for i in r.get("pr_covered_issues", [])] if pr_any: lines += [ @@ -491,6 +930,20 @@ def render_report( f"({pr.get('branch') or 'branch unknown'})" ) lines.append("") + verdict_any = [ + (r, i) for r in results for i in r.get("verdict_covered_issues", []) + ] + if verdict_any: + lines += [ + "## Covered by a recorded verdict — parked, no triage packet (#12233 F2b)", + "", + ] + for r, i in verdict_any: + lines.append( + f"- {r['repo']}#{i['number']} — verdict {i.get('verdict')} " + f"(resume {i.get('resume')})" + ) + lines.append("") uncovered_any = [(r, i) for r in results for i in r.get("uncovered_issues", [])] if uncovered_any: lines += ["## Uncovered issues", ""] @@ -560,6 +1013,12 @@ def main(argv: list[str] | None = None) -> int: results: list[dict] = [] errors: list[str] = [] + # Fixture mode only: canonical resume condition -> target state + # ("closed"/"open" for a dependency, "merged"/"open"/"closed" + # for a slice), so the resume-fulfilment check runs offline. An + # absent map is an empty map (unknown, never fulfilled), never a + # live lookup: fixtures must not touch the network. + resume_states = (fixture.get("resume_targets") or {}) if fixture else None for queue, repo in selected: try: if fixture: @@ -574,6 +1033,29 @@ def main(argv: list[str] | None = None) -> int: errors.append(str(exc)) continue + # A verdict read that failed leaves the issue's verdict + # unknown: it is skipped from the import below, never + # treated as verdict-free. + verdict_read_failed: set[int] = set() + if not fixture: + # #12233 F2b: the broker diff cannot see verdicts. For + # the effort issues it calls uncovered, read the recorded + # verdict from the issue's comments and merge it into the + # issue dict the verdict split below reads. A failed read + # is recorded as an error, never as "no verdict". + by_number = {i["number"]: i for i in issues} + for entry in cov.get("uncovered_issues", []): + issue = by_number.get(entry["number"]) + if issue is None or not ( + set(_issue_label_names(issue)) & VERDICT_EFFORT_LABELS + ): + continue + try: + issue.update(fetch_issue_verdict(repo, issue["number"])) + except FetchError as exc: + errors.append(str(exc)) + verdict_read_failed.add(issue["number"]) + # #4951: an issue the broker calls uncovered whose fix PR is # still open is in-flight, not ownerless — no triage packet. pr_coverage = build_pr_coverage(pulls) @@ -584,6 +1066,45 @@ def main(argv: list[str] | None = None) -> int: for i in broker_uncovered if i["number"] in pr_coverage ] + + # #12233 F2b: an issue the broker calls uncovered whose + # recorded verdict parks it is verdict-covered — the verdict + # note is the park record, so no triage packet. Two releases + # end the coverage: a timeline change after the verdict + # (verdict_fresh), and a fulfilled resume condition + # (resolve_resume). An unread verdict is neither covered nor + # uncovered — it is skipped from the import entirely. + by_number = {i["number"]: i for i in issues} + verdict_covered: list[dict] = [] + verdict_unread: list[dict] = [] + resume_fulfilled_issues: list[dict] = [] + stale_issues: list[dict] = [] + still_uncovered: list[dict] = [] + for entry in uncovered: + issue = by_number.get(entry["number"], entry) + if entry["number"] in verdict_read_failed: + verdict_unread.append(entry) + continue + info = verdict_coverage(issue) + if not info: + still_uncovered.append(entry) + continue + if not verdict_fresh(issue): + stale_issues.append({**entry, **info}) + still_uncovered.append(entry) + continue + try: + fulfilled = resolve_resume(repo, info["resume"], resume_states) + except FetchError as exc: + errors.append(str(exc)) + fulfilled = None + if fulfilled: + resume_fulfilled_issues.append({**entry, **info}) + still_uncovered.append(entry) + else: + verdict_covered.append({**entry, **info}) + uncovered = still_uncovered + imported = 0 if do_import and uncovered: for issue in uncovered: @@ -620,6 +1141,13 @@ def main(argv: list[str] | None = None) -> int: "covered": cov.get("covered", 0), "pr_covered": len(pr_covered), "pr_covered_issues": pr_covered, + "verdict_covered": len(verdict_covered), + "verdict_covered_issues": verdict_covered, + "verdict_unread": len(verdict_unread), + "verdict_unread_issues": verdict_unread, + "resume_fulfilled": len(resume_fulfilled_issues), + "resume_fulfilled_issues": resume_fulfilled_issues, + "stale_issues": stale_issues, "uncovered": len(uncovered), "imported": imported, "watch_imported": watch_imported, diff --git a/scripts/fleet/queue-reconcile/test_check_coverage.py b/scripts/fleet/queue-reconcile/test_check_coverage.py index 24ed29844c..a961f1f550 100644 --- a/scripts/fleet/queue-reconcile/test_check_coverage.py +++ b/scripts/fleet/queue-reconcile/test_check_coverage.py @@ -13,7 +13,10 @@ the queue's dedupe key, but the script must not double-submit within a run or across runs given the same coverage answer); - a fetch failure is an ERROR with exit 3, never a silent "0 uncovered"; -- the triage packet is schema-shaped and carries the issue dedupe basis. +- the triage packet is schema-shaped and carries the issue dedupe basis; +- an open PR covers its issue with a merge-watch packet, not triage; +- a recorded verdict with a resume condition covers an effort/l or + effort/m issue (#12233 F2b), and an issue with no verdict does not. """ import importlib.util @@ -383,5 +386,485 @@ def test_pr_signal_mapping(self): ) +class VerdictCoverageTest(unittest.TestCase): + """#12233 F2b: a triaged large issue is covered by its recorded + verdict and not re-enqueued; an issue with no verdict is still + uncovered. The broker diff cannot see verdicts, so the fixture + carries them on the issue objects (labels / verdict / + resume_condition), exactly as the live enrichment merges them.""" + + def setUp(self): + self.tmp = Path(tempfile.mkdtemp()) + self.fleet = StubFleet(self.tmp) + self.state = self.tmp / "state" + self.base = CoverageReconcileTest("test_observe_mode_imports_nothing") + self.base.tmp = self.tmp + self.base.fleet = self.fleet + self.base.state = self.state + + def run_cli(self, fx: dict, *extra: str): + return self.base.run_cli(fx, *extra) + + @staticmethod + def vfixture( + entries: dict, uncovered: list[int], resume_targets: dict | None = None + ) -> dict: + issues = [ + {"number": n, "title": f"issue {n}", **extra} + for n, extra in entries.items() + ] + covered = [n for n in entries if n not in uncovered] + fx = { + "issues": {REPO: issues}, + "pulls": {REPO: []}, + "coverage": { + REPO: { + "queue": QUEUE, + "repo": REPO, + "open_issues": len(issues), + "covered": len(covered), + "uncovered": len(uncovered), + "covered_issues": [{"number": n} for n in covered], + "uncovered_issues": [ + { + "number": n, + "title": f"issue {n}", + "url": f"https://github.com/{REPO}/issues/{n}", + } + for n in uncovered + ], + } + }, + } + if resume_targets is not None: + fx["resume_targets"] = resume_targets + return fx + + def test_verdict_covered_issue_is_not_reenqueued(self): + # The F2b done-test: a triaged large issue is covered. + fx = self.vfixture( + { + 3: { + "labels": ["effort/l"], + "verdict": "still_blocked", + "resume_condition": "dependency_closed:539", + } + }, + [3], + ) + code, out = self.run_cli(fx, "--import") + self.assertEqual(code, 0) + self.assertEqual(self.fleet.calls(), []) + self.assertIn("Total uncovered: 0", out) + self.assertIn("Verdict covered (#12233 F2b): 1", out) + self.assertIn(f"{REPO}#3", out) + + def test_issue_with_no_verdict_is_still_uncovered(self): + # The other half of the F2b done-test. + fx = self.vfixture({4: {"labels": ["effort/l"]}}, [4]) + code, _ = self.run_cli(fx, "--import") + self.assertEqual(code, 0) + calls = self.fleet.calls() + self.assertEqual(len(calls), 1) + self.assertEqual(calls[0]["packet"]["payload"]["kind"], "triage") + self.assertEqual(calls[0]["packet"]["payload"]["issue"]["number"], 4) + + def test_verdict_without_resume_condition_is_still_uncovered(self): + fx = self.vfixture( + {5: {"labels": ["effort/m"], "verdict": "still_blocked"}}, [5] + ) + code, _ = self.run_cli(fx, "--import") + self.assertEqual(code, 0) + self.assertEqual(len(self.fleet.calls()), 1) + + def test_small_issue_verdict_does_not_cover(self): + fx = self.vfixture( + { + 6: { + "labels": ["effort/s"], + "verdict": "still_blocked", + "resume_condition": "dependency_closed:539", + } + }, + [6], + ) + code, _ = self.run_cli(fx, "--import") + self.assertEqual(code, 0) + self.assertEqual(len(self.fleet.calls()), 1) + + def test_placeholder_verdict_does_not_cover(self): + fx = self.vfixture( + { + 7: { + "labels": ["effort/l"], + "verdict": "untriaged", + "resume_condition": "dependency_closed:539", + } + }, + [7], + ) + code, _ = self.run_cli(fx, "--import") + self.assertEqual(code, 0) + self.assertEqual(len(self.fleet.calls()), 1) + + def test_fulfilled_dependency_releases_coverage(self): + # Thread 1 (P1): #539 closed, so the verdict's wait is over — + # the parent is uncovered again and gets a triage packet. + fx = self.vfixture( + { + 3: { + "labels": ["effort/l"], + "verdict": "still_blocked", + "resume_condition": "dependency_closed:539", + } + }, + [3], + resume_targets={"dependency_closed:539": "closed"}, + ) + code, out = self.run_cli(fx, "--import") + self.assertEqual(code, 0) + calls = self.fleet.calls() + self.assertEqual(len(calls), 1) + self.assertEqual(calls[0]["packet"]["payload"]["issue"]["number"], 3) + self.assertIn("Total uncovered: 1", out) + self.assertIn("resume condition fulfilled", out) + + def test_open_dependency_keeps_coverage(self): + fx = self.vfixture( + { + 3: { + "labels": ["effort/l"], + "verdict": "still_blocked", + "resume_condition": "dependency_closed:539", + } + }, + [3], + resume_targets={"dependency_closed:539": "open"}, + ) + code, out = self.run_cli(fx, "--import") + self.assertEqual(code, 0) + self.assertEqual(self.fleet.calls(), []) + self.assertIn("Total uncovered: 0", out) + + def test_merged_slice_releases_coverage(self): + fx = self.vfixture( + { + 3: { + "labels": ["effort/l"], + "verdict": "still_blocked", + "resume_condition": "slice_landed:12543", + } + }, + [3], + resume_targets={"slice_landed:12543": "merged"}, + ) + code, _ = self.run_cli(fx, "--import") + self.assertEqual(code, 0) + self.assertEqual(len(self.fleet.calls()), 1) + + def test_closed_unmerged_slice_keeps_coverage(self): + # A slice PR closed without merging did not land the slice. + fx = self.vfixture( + { + 3: { + "labels": ["effort/l"], + "verdict": "still_blocked", + "resume_condition": "slice_landed:12543", + } + }, + [3], + resume_targets={"slice_landed:12543": "closed"}, + ) + code, _ = self.run_cli(fx, "--import") + self.assertEqual(code, 0) + self.assertEqual(self.fleet.calls(), []) + + def test_unknown_resume_state_keeps_coverage(self): + # No resume_targets entry: fulfilment is unknown, never + # assumed — and the fixture run touches no network. + fx = self.vfixture( + { + 3: { + "labels": ["effort/l"], + "verdict": "still_blocked", + "resume_condition": "dependency_closed:539", + } + }, + [3], + resume_targets={}, + ) + code, _ = self.run_cli(fx, "--import") + self.assertEqual(code, 0) + self.assertEqual(self.fleet.calls(), []) + + def test_stale_verdict_is_uncovered_again(self): + # Thread 2 (P1): a label change after the verdict ends it. + fx = self.vfixture( + { + 3: { + "labels": ["effort/l"], + "verdict": "still_blocked", + "resume_condition": "dependency_closed:539", + "verdict_at": "2026-11-08T12:00:00Z", + "timeline_changes": [ + {"kind": "label", "at": "2026-11-08T12:30:00Z"} + ], + } + }, + [3], + ) + code, out = self.run_cli(fx, "--import") + self.assertEqual(code, 0) + self.assertEqual(len(self.fleet.calls()), 1) + self.assertIn("verdict stale", out) + + def test_change_before_the_verdict_keeps_coverage(self): + fx = self.vfixture( + { + 3: { + "labels": ["effort/l"], + "verdict": "still_blocked", + "resume_condition": "dependency_closed:539", + "verdict_at": "2026-11-08T12:00:00Z", + "timeline_changes": [ + {"kind": "commit", "at": "2026-11-08T11:00:00Z"} + ], + } + }, + [3], + ) + code, _ = self.run_cli(fx, "--import") + self.assertEqual(code, 0) + self.assertEqual(self.fleet.calls(), []) + + def test_verdict_from_comments_records_verdict_time(self): + note = ( + "\nTriaged." + ) + comments = [ + { + "body": note, + "created_at": "2026-11-08T12:00:00Z", + "user": {"type": "User"}, + } + ] + self.assertEqual( + check_coverage.verdict_from_comments(comments), + { + "verdict": "still_blocked", + "resume_condition": "dependency_closed:539", + "verdict_at": "2026-11-08T12:00:00Z", + }, + ) + + def test_fetch_issue_verdict_applies_timeline_freshness(self): + # Thread 2 (P1) at the fetch level: the timeline is read and + # a change after the verdict voids it. + import subprocess as sp + import unittest.mock + + note = ( + "\nTriaged." + ) + + def fake_run(cmd, **kw): + if "timeline" in " ".join(cmd): + return sp.CompletedProcess( + cmd, + 0, + stdout=json.dumps( + { + "event": "labeled", + "created_at": "2026-11-08T12:30:00Z", + "commit_id": None, + } + ) + + "\n", + stderr="", + ) + return sp.CompletedProcess( + cmd, + 0, + stdout=json.dumps( + { + "body": note, + "created_at": "2026-11-08T12:00:00Z", + "user": {"type": "User"}, + } + ) + + "\n", + stderr="", + ) + + with unittest.mock.patch.object( + check_coverage.subprocess, "run", side_effect=fake_run + ): + stale = check_coverage.fetch_issue_verdict(REPO, 3) + self.assertEqual(stale["verdict"], "still_blocked") + self.assertFalse(check_coverage.verdict_fresh(stale)) + + def test_fetch_resume_state_reads_unquoted_dependency_state(self): + # Codex P1 on #12565: `--jq .state` emits the raw state word + # (`closed` / `open`), not JSON — decoding it as JSON raised + # on every live lookup and left closed dependencies unknown. + import subprocess as sp + import unittest.mock + + seen = [] + + def fake_run(cmd, **kw): + seen.append(cmd) + if "/issues/" in " ".join(cmd): + return sp.CompletedProcess( + cmd, 0, stdout="closed\n", stderr="" + ) + return sp.CompletedProcess( + cmd, + 0, + stdout=json.dumps({"merged": True, "state": "closed"}) + "\n", + stderr="", + ) + + with unittest.mock.patch.object( + check_coverage.subprocess, "run", side_effect=fake_run + ): + state = check_coverage.fetch_resume_state( + REPO, "dependency_closed:539" + ) + self.assertEqual(state, "closed") + self.assertTrue( + check_coverage.resolve_resume(REPO, "dependency_closed:539") + ) + self.assertEqual( + check_coverage.fetch_resume_state(REPO, "slice_landed:12543"), + "merged", + ) + dep_cmd = [c for c in seen if "/issues/" in " ".join(c)][0] + self.assertEqual(dep_cmd[-2:], ["--jq", ".state"]) + + def test_fetch_resume_state_open_dependency_is_not_fulfilled(self): + import subprocess as sp + import unittest.mock + + def fake_run(cmd, **kw): + return sp.CompletedProcess(cmd, 0, stdout="open\n", stderr="") + + with unittest.mock.patch.object( + check_coverage.subprocess, "run", side_effect=fake_run + ): + self.assertEqual( + check_coverage.fetch_resume_state(REPO, "dependency_closed:539"), + "open", + ) + self.assertFalse( + check_coverage.resolve_resume(REPO, "dependency_closed:539") + ) + + def test_unread_verdict_issue_is_skipped_from_import(self): + # Thread 3 (P2): the comments fetch fails, so the issue's + # verdict is unknown — no triage packet, exit 3. + import unittest.mock + + token = self.tmp / "token" + token.write_text("test-token\n") + coverage = { + "queue": QUEUE, + "repo": REPO, + "open_issues": 1, + "covered": 0, + "uncovered": 1, + "covered_issues": [], + "uncovered_issues": [ + { + "number": 3, + "title": "issue 3", + "url": f"https://github.com/{REPO}/issues/3", + } + ], + } + with ( + unittest.mock.patch.object( + check_coverage, + "fetch_open_issues", + return_value=[ + {"number": 3, "title": "issue 3", "labels": ["effort/l"]} + ], + ), + unittest.mock.patch.object( + check_coverage, "fetch_open_prs", return_value=[] + ), + unittest.mock.patch.object( + check_coverage, "broker_coverage", return_value=coverage + ), + unittest.mock.patch.object( + check_coverage, + "fetch_issue_verdict", + side_effect=check_coverage.FetchError( + "github comments failed for developing-today/code#3: boom" + ), + ), + ): + import io + from contextlib import redirect_stdout, redirect_stderr + + buf = io.StringIO() + with redirect_stdout(buf), redirect_stderr(buf): + code = check_coverage.main( + [ + "--import", + "--state-dir", + str(self.state), + "--fleet", + str(self.fleet.bin), + "--repo", + REPO, + "--token-file", + str(token), + "--now", + "2026-11-08T13:00:00Z", + ] + ) + out = buf.getvalue() + self.assertEqual(code, 3) + self.assertEqual(self.fleet.calls(), []) + self.assertIn("Total uncovered: 0", out) + self.assertIn("Verdict unread", out) + self.assertIn("github comments failed", out) + + def test_parse_resume_condition_forms(self): + parse = check_coverage.parse_resume_condition + self.assertEqual(parse("dependency_closed:539"), "dependency_closed:539") + self.assertEqual(parse("slice landed #12543"), "slice_landed:12543") + self.assertEqual( + parse({"kind": "dependency_closed", "target": "#539"}), + "dependency_closed:539", + ) + for bad in ("next week", "2027-01-01", "the owner", "slice_landed", None, ""): + with self.subTest(bad=bad): + self.assertIsNone(parse(bad)) + + def test_verdict_from_comments_reads_the_newest_note(self): + note = ( + "\nTriaged." + ) + comments = [{"body": note, "user": {"type": "User"}}] + self.assertEqual( + check_coverage.verdict_from_comments(comments), + {"verdict": "still_blocked", "resume_condition": "dependency_closed:539"}, + ) + # A human comment after the verdict ends its coverage. + comments.append({"body": "take another look", "user": {"type": "User"}}) + self.assertEqual(check_coverage.verdict_from_comments(comments), {}) + # A bot comment does not. + comments[1] = {"body": "CI summary", "user": {"type": "Bot"}} + self.assertEqual( + check_coverage.verdict_from_comments(comments)["verdict"], + "still_blocked", + ) + + if __name__ == "__main__": unittest.main()