Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions docs/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,15 @@ Publishing then works as follows, with the §5 signing unchanged:
that target alone. GitHub answers a fork request for a parent the
organisation already forks with the existing fork, and the
reply's name, not the target's, is the one renamed or polled.
The job polls every fork it requested or renamed against one
shared one-minute deadline. It records one still answering 404
then, after a request GitHub accepted, as `requested; not yet
visible` with a warning rather than a failure: GitHub can take
longer to fork a large repository, and the publish job, which
starts after the author session, reads the fork again. A fork
renamed with no request behind it, still 404 then, fails the
target, as does any other read failure while polling, 410 Gone
included.
Creating or renaming a fork needs Administration: write on the
fork organisation, and a GitHub App holds its permissions on
every installation at once: an App able to create forks could
Expand Down
4 changes: 3 additions & 1 deletion scripts/branch_refs.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,9 @@ def missing_fork(fork: str) -> str:
"""The reason a publish fails when the fork it needs does not exist."""
return (
f"fork {fork} does not exist; the Prepare forks job creates it, "
"so read that job's log, or create the fork by hand"
"so read that job's log, or create the fork by hand. Either that "
"job failed to ready it, or it recorded the fork as requested; "
"not yet visible and GitHub may still be creating it"
)


Expand Down
67 changes: 58 additions & 9 deletions scripts/fork_pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@
attempted; a failure on one is reported and the rest go ahead, so the
publisher can still publish to the forks that are ready. The exit
status is 1 when any target failed, and 0 with a warning when no
token was provided at all.
token was provided at all. A fork GitHub accepted but has not shown
by the deadline warns rather than fails: GitHub can take longer than
that to fork a large repository, and the publish job reads it again.
"""

from __future__ import annotations
Expand Down Expand Up @@ -128,18 +130,35 @@ def check_rename_rights(found: str, fork_org: str, account: str) -> None:
)


class NotYetVisible(PublishError):
"""A fork GitHub accepted the request for but has not shown yet.

Forking a large repository can take longer than the forks job
waits, and the publish job reads the fork again much later, so
this is a warning, not a failure.
"""


def await_fork(fork: str, deadline: float) -> dict[str, Any]:
"""Poll for a fork GitHub is still creating until ``deadline``.

Forking is asynchronous. Every fork a run requested shares one
deadline, so the waits overlap rather than add up.
deadline, so the waits overlap rather than add up. Only a 404 is a
fork still being made: a fork still 404 at the deadline raises
:class:`NotYetVisible`, and any other read failure, 410 Gone
included, is a :class:`PublishError`.
"""
while True:
try:
return github.api_object(f"repos/{fork}")
except github.GitHubError as exc:
if not github.is_absent(exc) or time.monotonic() >= deadline:
if exc.status != 404:
raise PublishError(f"fork {fork} did not appear: {exc}") from exc
if time.monotonic() >= deadline:
raise NotYetVisible(
f"fork {fork} requested; not yet visible after "
f"{FORK_WAIT_SECONDS} seconds"
) from exc
time.sleep(FORK_POLL_SECONDS)


Expand All @@ -166,10 +185,16 @@ def create_fork(target: str, fork_org: str) -> str:


class Pending(NamedTuple):
"""A fork requested or renamed, which GitHub may still be making."""
"""A fork requested or renamed, which GitHub may still be making.

``requested`` is true when GitHub accepted a fork request for it;
only such a fork may still be absent at the deadline without
failing.
"""

target: Target
outcome: str
requested: bool


def start(target: Target, account: str) -> str | Pending:
Expand Down Expand Up @@ -210,16 +235,29 @@ def start(target: Target, account: str) -> str | Pending:
f"could not rename fork {found} to {target.repo_name}: {exc}"
) from exc
if listed is not None:
return Pending(target, f"renamed from {listed}")
return Pending(target, f"renamed from {listed}", requested=False)
if found.lower() != fork.lower():
return Pending(target, f"created as {found}, then renamed")
return Pending(target, "created")
return Pending(target, f"created as {found}, then renamed", requested=True)
return Pending(target, "created", requested=True)


def finish(pending: Pending, deadline: float) -> str:
"""Wait for a pending fork and prove it is the target's."""
"""Wait for a pending fork and prove it is the target's.

A fork renamed with no fork request behind it fails when still
absent at the deadline: nothing is creating it.
"""
target = pending.target
if not refs.is_fork_of(await_fork(target.fork, deadline), target.repository):
try:
data = await_fork(target.fork, deadline)
except NotYetVisible as exc:
if pending.requested:
raise
raise PublishError(
f"fork {target.fork} did not appear within {FORK_WAIT_SECONDS} "
f"seconds of its {pending.outcome}"
) from exc
if not refs.is_fork_of(data, target.repository):
raise PublishError(
f"{target.fork} exists but is not a fork of {target.repository}"
)
Expand Down Expand Up @@ -249,6 +287,15 @@ def fail(self, fork: str, exc: Exception) -> None:
print(f"::error title=Fork not ready::{fork}: {outcome}")
self.write(fork, outcome)

def pending(self, fork: str) -> None:
"""Log and append a requested fork GitHub has not shown yet."""
outcome = "requested; not yet visible"
print(
f"::warning title=Fork not yet visible::{fork}: {outcome}; GitHub "
"may still be creating it, and the publish job reads it again"
)
self.write(fork, outcome)

def write(self, fork: str, outcome: str) -> None:
"""Append one row to the step summary."""
if self.path is not None:
Expand Down Expand Up @@ -295,6 +342,8 @@ def run_prepare(args: argparse.Namespace) -> int:
for pending in waiting:
try:
summary.record(pending.target.fork, finish(pending, deadline))
except NotYetVisible:
summary.pending(pending.target.fork)
Comment thread
lf-releng-code-monkey-bot[bot] marked this conversation as resolved.
Resolved
except (PublishError, github.GitHubError) as exc:
summary.fail(pending.target.fork, exc)
return 1 if summary.failed else 0
Expand Down
84 changes: 81 additions & 3 deletions tests/test_fork_pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,24 @@ def test_fork_under_an_old_name_is_renamed(self) -> None:
self.assertEqual(read.call_args_list[1].args, (f"repos/{old}",))
self.assertEqual(read.call_args_list[-1].args, (f"repos/{FORK}",))

def test_renamed_fork_still_absent_at_the_deadline_fails(self) -> None:
"""A rename with no fork request behind it never warns as not yet visible."""
listed = [{"full_name": OLD, "owner": {"login": FORK_ORG}}]
admin = repo_object(full_name=OLD, permissions={"admin": True})
with (
patch.object(github, "api_object", side_effect=[absent(), admin, absent()]),
patch.object(github, "api_list", return_value=listed),
patch.object(github, "api_write", return_value={}) as write,
patch.object(pool.time, "sleep"),
patch.object(pool.time, "monotonic", side_effect=past_deadline()),
self.assertRaisesRegex(
policy.PublishError, f"did not appear .* renamed from {OLD}"
) as raised,
):
prepare(TARGET_ENTRY)
self.assertNotIsInstance(raised.exception, pool.NotYetVisible)
write.assert_called_once_with("PATCH", f"repos/{OLD}", {"name": "repo"})

def test_listed_fork_without_admin_is_not_renamed(self) -> None:
"""A pool fork the account cannot administer fails, naming the right it lacks."""
listed = [{"full_name": OLD, "owner": {"login": FORK_ORG}}]
Expand Down Expand Up @@ -489,8 +507,8 @@ def test_fork_request_failure_is_operational(self) -> None:
prepare(TARGET_ENTRY)
sleep.assert_not_called()

def test_poll_timeout_is_operational(self) -> None:
"""A fork that never appears before the deadline is an error."""
def test_poll_timeout_is_not_yet_visible(self) -> None:
"""A requested fork still absent at the deadline is told apart from a failure."""
with (
patch.object(github, "api_object", side_effect=absent()),
patch.object(github, "api_list", return_value=[]),
Expand All @@ -501,10 +519,25 @@ def test_poll_timeout_is_operational(self) -> None:
"monotonic",
side_effect=[0.0, 1.0, pool.FORK_WAIT_SECONDS + 1.0],
),
self.assertRaisesRegex(policy.PublishError, "did not appear"),
self.assertRaisesRegex(pool.NotYetVisible, "not yet visible"),
):
prepare(TARGET_ENTRY)

def test_poll_read_failure_is_operational(self) -> None:
"""A 500 or a 410 while polling is a failure, not a fork still being made."""
for status in (500, 410):
failure = github.GitHubError(f"x (HTTP {status})")
with (
self.subTest(status=status),
patch.object(github, "api_object", side_effect=[absent(), failure]),
patch.object(github, "api_list", return_value=[]),
patch.object(github, "api_write", return_value=repo_object()),
patch.object(pool.time, "sleep"),
patch.object(pool.time, "monotonic", return_value=0.0),
self.assertRaisesRegex(policy.PublishError, "did not appear"),
):
prepare(TARGET_ENTRY)

def test_created_repository_must_still_be_a_fork(self) -> None:
"""What appears after the request is checked like a found one."""
with (
Expand Down Expand Up @@ -594,6 +627,51 @@ def test_one_failure_fails_the_job_after_every_target(self) -> None:
self.assertIn(f"| `{FORK}` | failed: ", summary)
self.assertIn(f"| `{FORK_ORG}/other` | present |", summary)

def test_a_fork_not_yet_visible_warns_and_passes(self) -> None:
"""GitHub can take over a minute to fork; the publish job reads it later."""
env = {"GH_TOKEN": "t", "MATRIX": matrix(entry())}
out = io.StringIO()
with (
patch.object(github, "run_gh", return_value=SCOPED),
patch.object(github, "api_object", side_effect=absent()),
patch.object(github, "api_list", return_value=[]),
patch.object(github, "api_write", return_value=repo_object()),
patch.object(pool.time, "sleep"),
patch.object(
pool.time, "monotonic", side_effect=[0.0, pool.FORK_WAIT_SECONDS + 1.0]
),
redirect_stdout(out),
):
self.assertEqual(self.run_main(env), 0)
self.assertIn(f"::warning title=Fork not yet visible::{FORK}", out.getvalue())
self.assertNotIn("::error", out.getvalue())
self.assertIn(
f"| `{FORK}` | requested; not yet visible |", self.summary.read_text()
)

def test_a_refused_or_wrong_fork_still_fails_the_job(self) -> None:
"""Only a slow fork is spared: a refusal or a non-fork still exits 1."""
env = {"GH_TOKEN": "t", "MATRIX": matrix(entry())}
refused = github.GitHubError("gh: Forbidden (HTTP 403)")
cases = {
"refused": ([absent()], refused),
"not a fork": ([absent(), repo_object(fork=False)], repo_object()),
}
for name, (reads, created) in cases.items():
self.summary.unlink(missing_ok=True)
with (
self.subTest(name),
patch.object(github, "run_gh", return_value=SCOPED),
patch.object(github, "api_object", side_effect=reads),
patch.object(github, "api_list", return_value=[]),
patch.object(github, "api_write", side_effect=[created]),
patch.object(pool.time, "sleep"),
patch.object(pool.time, "monotonic", return_value=0.0),
redirect_stdout(io.StringIO()),
):
self.assertEqual(self.run_main(env), 1)
self.assertIn(f"| `{FORK}` | failed: ", self.summary.read_text())

def test_a_wrong_token_stops_before_any_fork(self) -> None:
"""A token with broader scopes exits 1 before reading a fork."""
env = {"GH_TOKEN": "t", "MATRIX": matrix(entry())}
Expand Down
9 changes: 7 additions & 2 deletions tests/test_fork_publish.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,13 +73,18 @@ def test_existing_fork_passes_with_one_read(self) -> None:
write.assert_not_called()

def test_missing_fork_names_the_forks_job(self) -> None:
"""A 404 is neither created nor looked up by parent; it is reported."""
"""A 404 is neither created nor looked up by parent; it is reported.

The reason names both causes: the forks job failed, or it
recorded a fork GitHub was still creating.
"""
with (
patch.object(github, "api_object", side_effect=absent()),
patch.object(github, "api_list") as listing,
patch.object(github, "api_write") as write,
self.assertRaisesRegex(
policy.PublishError, f"fork {FORK} does not exist.*Prepare forks"
policy.PublishError,
f"fork {FORK} does not exist.*Prepare forks.*not yet visible",
),
):
refs.require_fork(FORK, TARGET)
Expand Down
Loading