Answer principles round 1: 1 🔴, 7 🟡 (0 misread); every effect is handed in as an argument, no test patches a global, and the traces principle scopes tools that run on their user's machine
CI / tests (pull_request) Successful in 3m43s

This commit is contained in:
2026-11-19 12:42:03 +01:00
parent 8ca612b7a4
commit cb3135bc8c
124 changed files with 1437 additions and 793 deletions
+1 -2
View File
@@ -2,7 +2,6 @@
import dataclasses
import fnmatch
import json
import time
import typing
from failure import Failure
@@ -104,7 +103,7 @@ def checks_now(forge: Forge, number: str, head: str, required: set[str], run: Ru
return None if (count == 0 and settled or state == "success") and not missing else Pending(missing)
def checks_passed(forge: Forge, number: str, head: str, required: set[str], run: Run, sleep: typing.Callable[[float], None] = time.sleep, settle: int = 0) -> Failure | None:
def checks_passed(forge: Forge, number: str, head: str, required: set[str], run: Run, sleep: typing.Callable[[float], None], settle: int = 0) -> Failure | None:
"""None once every check on pull request number, whose head commit is head, has passed, or where it has none for settle seconds; a Failure where one fails, or where they have not all passed within WAIT_SECONDS. checks_now says what counts as passed on Gitea."""
if forge == "gh":
for waited in range(0, settle + 1, POLL_SECONDS):
+79 -21
View File
@@ -1,6 +1,6 @@
"""A pull request's review state, read once from its forge: the review decision, whether it is a draft, whether the worker answered the changes a reviewer requested, and the review threads that wait for an answer. chunk-pr and do-epic decide on what this reads, and run no review query of their own."""
import dataclasses
import json
import typing
from failure import Failure
from forge.commands import Forge, gitea, Run
@@ -42,28 +42,64 @@ def answered_decision(pull: str, head: str, run: Run) -> str | None | Failure:
viewed = run(["gh", "pr", "view", pull, "--json", "isDraft,reviewDecision,author,reviews,comments"])
if isinstance(viewed, Failure):
return viewed
view = pull_view(viewed)
if isinstance(view, Failure):
return view
if view.draft:
return None
return ANSWERED if view.decision == CHANGES_REQUESTED and answered(view, head) else view.decision
@dataclasses.dataclass(frozen=True)
class Review:
"""One review of a pull request. GitHub lists a reply in a thread as a review of its own."""
author: str
state: str
# Empty for a review its author has yet to submit.
submitted_at: str
# The commit a review that requested changes was made on; empty for any other review.
commit: str
@dataclasses.dataclass(frozen=True)
class PullView:
"""A pull request as `gh pr view --json isDraft,reviewDecision,author,reviews,comments` prints it."""
draft: bool
# Empty where its branch protection asks for no review.
decision: str
reviews: tuple[Review, ...]
# When its author submitted each review and made each comment. A review the author has yet to submit has no time: it is empty, and answers nobody.
said: tuple[str, ...]
def text(value: object) -> str:
"""value, which a forge's answer must hold as a string. Raises TypeError where it is none."""
if not isinstance(value, str):
raise TypeError(f"{value!r} is not a string")
return value
def pull_view(printed: str) -> PullView | Failure:
"""The pull request that gh printed, with each field checked here, so what decides on it meets no other shape."""
try:
parsed = json.loads(viewed)
if parsed["isDraft"]:
return None
decision = str(parsed["reviewDecision"] or "")
return ANSWERED if decision == CHANGES_REQUESTED and answered(parsed, head) else decision
pull = json.loads(printed)
author = text(pull["author"]["login"])
reviews = tuple(Review(text(review["author"]["login"]), text(review["state"]), text(review["submittedAt"] or ""), text(review["commit"]["oid"]) if review["state"] == CHANGES_REQUESTED else "") for review in pull["reviews"])
commented = tuple(text(comment["createdAt"]) for comment in pull["comments"] if text(comment["author"]["login"]) == author)
return PullView(bool(pull["isDraft"]), text(pull["reviewDecision"] or ""), reviews, tuple(review.submitted_at for review in reviews if review.author == author) + commented)
except (ValueError, KeyError, TypeError):
return Failure(f"gh pr view printed no review decision: {viewed.strip()[:200]}")
return Failure(f"gh pr view printed no review decision: {printed.strip()[:200]}")
def answered(pull: dict[str, typing.Any], head: str) -> bool:
"""Whether the worker answered the newest review that requested changes on pull, as `gh pr view --json author,reviews,comments` prints it, whose head commit is head: the head is no longer the commit that review was made on, or the pull request's author commented or replied in a thread after it. GitHub lists a reply in a thread as a review of its own. False where it lists no review that requested changes. Raises KeyError or TypeError where pull has another shape.
def answered(pull: PullView, head: str) -> bool:
"""Whether the worker answered the newest review that requested changes on pull, whose head commit is head: the head is no longer the commit that review was made on, or the pull request's author commented or replied in a thread after it. False where pull lists no review that requested changes.
The review names its commit, so no clock tells whether the worker pushed: a commit's date says when it was made, never when it was pushed.
"""
asked = max((review for review in pull["reviews"] if review["state"] == CHANGES_REQUESTED), key=lambda review: review["submittedAt"], default=None)
asked = max((review for review in pull.reviews if review.state == CHANGES_REQUESTED), key=lambda review: review.submitted_at, default=None)
if asked is None:
return False
author = pull["author"]["login"]
# A review the author has yet to submit has no time, and answers nobody.
said = [review["submittedAt"] or "" for review in pull["reviews"] if review["author"]["login"] == author] + [comment["createdAt"] for comment in pull["comments"] if comment["author"]["login"] == author]
return asked["commit"]["oid"] != head or any(at > asked["submittedAt"] for at in said)
return asked.commit != head or any(at > asked.submitted_at for at in pull.said)
def gitea_decision(pull: str, run: Run) -> str | None | Failure:
@@ -71,10 +107,10 @@ def gitea_decision(pull: str, run: Run) -> str | None | Failure:
viewed = gitea(run, f"repos/{{owner}}/{{repo}}/pulls/{pull}")
if isinstance(viewed, Failure):
return viewed
try:
return None if viewed["title"].upper().startswith(GITEA_DRAFT) else ""
except (KeyError, TypeError, AttributeError):
title = viewed.get("title") if isinstance(viewed, dict) else None
if not isinstance(title, str):
return Failure(f"tea api printed no title of pull request {pull}: {str(viewed)[:200]}")
return None if title.upper().startswith(GITEA_DRAFT) else ""
def waiting_threads(number: str, run: Run) -> list[str] | Failure:
@@ -82,9 +118,31 @@ def waiting_threads(number: str, run: Run) -> list[str] | Failure:
read = run(["gh", "api", "graphql", "-f", f"query={THREADS}", "-F", "owner={owner}", "-F", "repo={repo}", "-F", f"number={number}"])
if isinstance(read, Failure):
return read
threads = threads_read(read)
if isinstance(threads, Failure):
return threads
return waits(*threads)
@dataclasses.dataclass(frozen=True)
class Thread:
"""One review thread of a pull request."""
path: str
resolved: bool
# Who wrote its last comment; empty for a thread without one.
last: tuple[str, ...]
def threads_read(printed: str) -> tuple[str, tuple[Thread, ...]] | Failure:
"""Who opened the pull request and its review threads, as gh printed THREADS' answer, with each field checked here."""
try:
pull = json.loads(read)["data"]["repository"]["pullRequest"]
author = pull["author"]["login"]
return sorted({thread["path"] for thread in pull["reviewThreads"]["nodes"] if not thread["isResolved"] and any(comment["author"]["login"] != author for comment in thread["comments"]["nodes"])})
pull = json.loads(printed)["data"]["repository"]["pullRequest"]
threads = tuple(Thread(text(thread["path"]), bool(thread["isResolved"]), tuple(text(comment["author"]["login"]) for comment in thread["comments"]["nodes"])) for thread in pull["reviewThreads"]["nodes"])
return text(pull["author"]["login"]), threads
except (ValueError, KeyError, TypeError):
return Failure(f"gh api graphql printed no review threads: {read.strip()[:200]}")
return Failure(f"gh api graphql printed no review threads: {printed.strip()[:200]}")
def waits(author: str, threads: tuple[Thread, ...]) -> list[str]:
"""The files of the threads that wait for an answer from author, who opened the pull request."""
return sorted({thread.path for thread in threads if not thread.resolved and any(last != author for last in thread.last)})
+102
View File
@@ -0,0 +1,102 @@
import json
import pathlib
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from forge.reviews import ANSWERED, CHANGES_REQUESTED, PullView, Review, Thread
from failure import Failure
from forge import reviews
ASKED = {"author": {"login": "rev"}, "state": CHANGES_REQUESTED, "submittedAt": "2026-11-02T10:00:00Z", "commit": {"oid": "abc"}}
PULL = {"isDraft": False, "reviewDecision": CHANGES_REQUESTED, "author": {"login": "me"}, "reviews": [ASKED], "comments": []}
def printing(answer: object):
"""A run whose command prints answer as JSON."""
return lambda args: json.dumps(answer)
class Faulty:
"""A pull request's number or head whose use in a comparison or in a command raises a fault of our own."""
def __ne__(self, other: object) -> bool:
raise TypeError("ours")
def __format__(self, spec: str) -> str:
raise TypeError("ours")
class ThePullRequestAsViewed(unittest.TestCase):
def test_parses_what_gh_prints_into_one_value(self):
pending = {"author": {"login": "me"}, "state": "PENDING", "submittedAt": None, "commit": None}
printed = json.dumps(PULL | {"reviews": [ASKED, pending], "comments": [{"author": {"login": "me"}, "createdAt": "2026-11-02T11:00:00Z"}, {"author": {"login": "rev"}, "createdAt": "2026-11-02T12:00:00Z"}]})
self.assertEqual(reviews.pull_view(printed), PullView(False, CHANGES_REQUESTED, (Review("rev", CHANGES_REQUESTED, "2026-11-02T10:00:00Z", "abc"), Review("me", "PENDING", "", "")), ("", "2026-11-02T11:00:00Z")))
def test_an_answer_in_another_shape_is_a_failure_naming_what_gh_printed(self):
unshaped = ("not json", "[]", json.dumps(PULL | {"reviews": None}), json.dumps(PULL | {"author": None}), json.dumps(PULL | {"reviews": [ASKED | {"commit": None}]}), json.dumps(PULL | {"reviews": [ASKED | {"submittedAt": 7}]}), json.dumps({key: value for key, value in PULL.items() if key != "isDraft"}))
for printed in unshaped:
with self.subTest(printed=printed):
self.assertEqual(reviews.pull_view(printed), Failure(f"gh pr view printed no review decision: {printed[:200]}"))
self.assertEqual(reviews.answered_decision("7", "abc", lambda args: printed), Failure(f"gh pr view printed no review decision: {printed[:200]}"))
class WhetherTheWorkerAnswered(unittest.TestCase):
def view(self, *others: Review, said: tuple[str, ...] = ()) -> PullView:
return PullView(False, CHANGES_REQUESTED, (Review("rev", CHANGES_REQUESTED, "2026-11-02T10:00:00Z", "abc"), *others), tuple(review.submitted_at for review in others if review.author == "me") + said)
def test_a_new_head_or_a_later_word_of_the_authors_answers_the_newest_request(self):
self.assertFalse(reviews.answered(self.view(), "abc"))
self.assertTrue(reviews.answered(self.view(), "def"))
self.assertTrue(reviews.answered(self.view(said=("2026-11-02T10:30:00Z",)), "abc"))
self.assertFalse(reviews.answered(self.view(said=("2026-11-02T09:00:00Z", "")), "abc"))
self.assertTrue(reviews.answered(self.view(Review("me", "COMMENTED", "2026-11-02T10:30:00Z", "")), "abc"))
self.assertFalse(reviews.answered(PullView(False, "", (), ()), "abc"))
def test_the_decision_reads_answered_once_the_worker_answered(self):
self.assertEqual(reviews.answered_decision("7", "abc", printing(PULL)), CHANGES_REQUESTED)
self.assertEqual(reviews.answered_decision("7", "def", printing(PULL)), ANSWERED)
self.assertIsNone(reviews.answered_decision("7", "abc", printing(PULL | {"isDraft": True})))
self.assertEqual(reviews.answered_decision("7", "abc", printing(PULL | {"reviewDecision": None, "reviews": []})), "")
def test_a_fault_in_the_decision_is_not_reported_as_the_forges(self):
with self.assertRaisesRegex(TypeError, "ours"):
reviews.answered_decision("7", Faulty(), printing(PULL))
class TheThreadsThatWait(unittest.TestCase):
def printed(self, *threads: tuple[str, bool, str]) -> str:
nodes = [{"isResolved": resolved, "path": path, "comments": {"nodes": [{"author": {"login": last}}]}} for path, resolved, last in threads]
return json.dumps({"data": {"repository": {"pullRequest": {"author": {"login": "me"}, "reviewThreads": {"nodes": nodes}}}}})
def test_parses_what_gh_prints_into_the_author_and_each_thread(self):
self.assertEqual(reviews.threads_read(self.printed(("a.py", False, "rev"), ("b.py", True, "me"))), ("me", (Thread("a.py", False, ("rev",)), Thread("b.py", True, ("me",)))))
def test_a_thread_waits_while_unresolved_with_a_reviewers_last_word(self):
printed = self.printed(("b.py", False, "rev"), ("a.py", False, "rev"), ("a.py", False, "rev"), ("c.py", True, "rev"), ("d.py", False, "me"))
self.assertEqual(reviews.waiting_threads("7", lambda args: printed), ["a.py", "b.py"])
def test_an_answer_in_another_shape_is_a_failure_naming_what_gh_printed(self):
for printed in ("not json", "{}", json.dumps({"data": {"repository": {"pullRequest": {"author": {"login": "me"}, "reviewThreads": {"nodes": [{"isResolved": False}]}}}}})):
with self.subTest(printed=printed):
self.assertEqual(reviews.waiting_threads("7", lambda args: printed), Failure(f"gh api graphql printed no review threads: {printed[:200]}"))
def test_a_fault_in_the_choice_is_not_reported_as_the_forges(self):
with self.assertRaisesRegex(TypeError, "ours"):
reviews.waiting_threads(Faulty(), lambda args: self.printed(("a.py", False, "rev")))
class TheDecisionOnGitea(unittest.TestCase):
def decision(self, answer: object):
return reviews.gitea_decision("7", printing(answer))
def test_a_title_tells_a_draft_and_an_answer_without_one_is_a_failure(self):
self.assertIsNone(self.decision({"title": "wip: later"}))
self.assertEqual(self.decision({"title": "Fix it"}), "")
self.assertEqual(self.decision({"title": 7}), Failure("tea api printed no title of pull request 7: {'title': 7}"))
self.assertEqual(self.decision([]), Failure("tea api printed no title of pull request 7: []"))
if __name__ == "__main__":
unittest.main()