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
5 changes: 3 additions & 2 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -389,8 +389,9 @@ one state transition should not become repeated writes that trigger policy CI.
GitHub reads and the idempotent thread resolution mutation retry transient
failures once after five seconds. They stop on exhausted quota and honor a
secondary limit’s Retry-After when the delay fits the read budget. Mergify
reads retry server errors, throttling and failed
reads up to twice (2/5 seconds). Waits use bounded backoff. See the
queue reads retry once after two seconds, subject to Retry-After and the
remaining queue wait budget. Calls without a deadline allow less than five
seconds of backoff. See the
[contract's waiter and polling rules](../core/CONTRACT.md#failure).
The optional host ai-accounts helper owns managed credential selection and exact-model
eligibility under its existing lock. Its Claude exec reserve guard (including pinned
Expand Down
28 changes: 16 additions & 12 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,7 @@ def _readiness_precheck(wt: Path, config: Config, pr: github.PR, head: str, diag
def _readiness(
wt: Path, config: Config, pr: github.PR, head: str, reviews: list[dict] | None = None,
*, workflow_wait: bool = False, announce_receipt: bool = False, diagnostics: bool = False,
mergify_deadline: float | None = None,
) -> github.Readiness:
if problem := _readiness_precheck(wt, config, pr, head, diagnostics):
return github.Readiness(False, (problem,))
Expand Down Expand Up @@ -342,7 +343,7 @@ def _readiness(
if config.merge_strategy == "mergify" and pr.state == "OPEN":
behind = github.behind_reason(pr, head if review else None)
reasons = result.reasons
if mergify.configured(config.repo, config.base_branch, config.mergify_queue or ""):
if mergify.configured(config.repo, config.base_branch, config.mergify_queue or "", mergify_deadline):
reasons = tuple(reason for reason in reasons if reason != behind)
else:
reasons = (*reasons, "Mergify queue configuration is unverified or permits in-place head updates")
Expand Down Expand Up @@ -1189,15 +1190,18 @@ def _load_review(


def _pr_readiness(
wt: Path, config: Config, branch: str, *, allow_merged: bool = False, workflow_wait: bool = False
wt: Path, config: Config, branch: str, *, allow_merged: bool = False, workflow_wait: bool = False,
mergify_deadline: float | None = None,
) -> tuple[github.PR, github.Readiness | None]:
"""PR plus readiness; readiness is None only for an already merged PR (allow_merged)."""
head = worktree.head(wt)
_require_task_branch(config, branch)
pr = _require_pr(config, branch, allow_merged=allow_merged, list_only=True)
_require_pushed(pr, head)
readiness = None if pr.state == "MERGED" else _readiness(
wt, config, pr, head, workflow_wait=workflow_wait, announce_receipt=True)
wt, config, pr, head, workflow_wait=workflow_wait, announce_receipt=True,
mergify_deadline=mergify_deadline,
)
return pr, readiness


Expand Down Expand Up @@ -1497,7 +1501,8 @@ def _wait_for_checks(
previous = _verify_wait_snapshot(args, wt, config, pr.head_sha, current.head_sha, previous)
if allow_merged and current.state == "MERGED":
return current, None, kicked
readiness = _readiness(wt, config, current, pr.head_sha, workflow_wait=True)
readiness = _readiness(wt, config, current, pr.head_sha, workflow_wait=True,
mergify_deadline=started + timeout)
if not kicked and _draft_checks_waiting(config, current, readiness):
_require_receipt(wt, config, current.head_sha)
github.mark_ready(config.repo, pr.number)
Expand Down Expand Up @@ -1648,9 +1653,9 @@ def _wait_for_mergify(
sha = _landed(config, pr, closed)
if sha:
return sha
if not mergify.configured(config.repo, config.base_branch, queue):
if not mergify.configured(config.repo, config.base_branch, queue, started + timeout):
raise CliError("Mergify queue configuration became unsafe or unavailable while waiting")
state = mergify.membership(config.repo, pr.number, queue)
state = mergify.membership(config.repo, pr.number, queue, started + timeout)
deferred_landing_read = confirmed and state is not None and not closed
if not deferred_landing_read and (sha := _landed(config, pr, closed)):
return sha
Expand Down Expand Up @@ -1705,7 +1710,7 @@ def _merge_with_mergify(
requested, confirmed_marker = mergify.markers(
config.repo, pr.number, pr.head_sha, queue
)
state = mergify.membership(config.repo, pr.number, queue)
state = mergify.membership(config.repo, pr.number, queue, deadline)
if sha := github.merged_sha(
config.repo, pr.number, expected_head=pr.head_sha, check_hold=not requested and state is None,
):
Expand Down Expand Up @@ -1744,20 +1749,19 @@ def cmd_merge(args: argparse.Namespace) -> int:
mergify.dequeue(config.repo, pr.number)
print(f"requested removal of PR #{pr.number} from Mergify")
return 0
read_started = time.monotonic()
pr, readiness = _pr_readiness(
wt, config, branch, allow_merged=True, workflow_wait=args.wait is not None
)
started = time.monotonic()
deadline = None if args.wait is None else started + args.wait
pr, readiness = _pr_readiness(
wt, config, branch, allow_merged=True, workflow_wait=args.wait is not None, mergify_deadline=deadline,
)
# --wait=0 observes once; a positive budget also bounds merge or queue admission.
admit_by = deadline if args.wait else None
if readiness is not None and args.wait is not None and _pending_checks(config, pr, readiness):
# One waiter and one deadline span source checks and landing: a check created
# by the ready transition must not end the turn between `ready` and the queue.
waited = _wait_with_deadline(wt, config, pr, args.wait, kicked=False, started=started,
args=args, allow_merged=True, initial=readiness,
initial_read_time=started - read_started)
initial_read_time=time.monotonic() - started)
if waited is None:
return 3
pr, readiness, _ = waited
Expand Down
18 changes: 12 additions & 6 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -333,15 +333,21 @@ def _retry_pause(delay: float | None, limit: float, *, scoped: bool = True) -> b
return True


def _rate_limit_delay(headers: dict[str, str], delay: float | None) -> float | None:
if delay is None or headers.get("x-ratelimit-remaining") == "0":
return None
value = headers.get("retry-after", "")
def retry_after(value: str) -> float | None:
try:
wait = int(value) if re.fullmatch(r"[0-9]{1,18}", value) else parsedate_to_datetime(value).timestamp() - time.time()
if re.fullmatch(r"[0-9]{1,18}", value):
return float(value)
date = parsedate_to_datetime(value)
return max(0.0, date.timestamp() - time.time()) if date.tzinfo is not None else None
except (OverflowError, OSError, ValueError):
return None
return max(delay, wait)


def _rate_limit_delay(headers: dict[str, str], delay: float | None) -> float | None:
if delay is None or headers.get("x-ratelimit-remaining") == "0":
return None
wait = retry_after(headers.get("retry-after", ""))
return None if wait is None else max(delay, wait)


def _pr_list_error_guidance(args: tuple[str, ...], stderr: str, using_app: bool) -> str:
Expand Down
51 changes: 33 additions & 18 deletions src/loopzero/mergify.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,31 +109,46 @@ def _api_request(repo: str, suffix: str, method: str | None = None) -> urllib.re
)


def api_get(repo: str, suffix: str) -> object | None:
def _wait_to_retry(delay: float, deadline: float | None) -> bool:
remaining = 5.0 if deadline is None else deadline - time.monotonic()
if delay >= remaining:
return False
_retry_sleep(delay)
return deadline is None or time.monotonic() < deadline


def _queue_read_failure(exc: Exception) -> tuple[str, bool]:
if isinstance(exc, (json.JSONDecodeError, UnicodeDecodeError)):
return "Mergify queue lookup returned no valid JSON", True
reason = exc.reason if isinstance(exc, urllib.error.URLError) else exc
return f"Mergify queue transport failed: {reason}", not isinstance(reason, ssl.SSLCertVerificationError)


def api_get(repo: str, suffix: str, deadline: float | None = None) -> object | None:
"""GET one documented endpoint below this repository's fixed Mergify API path."""
if not suffix.startswith("/") or "://" in suffix or ".." in suffix:
raise ValueError("Mergify API suffix must be a repository-relative absolute path")
request = _api_request(repo, suffix)
for delay in (2.0, 5.0, None): # reads retry server errors, throttling and dropped reads
for retry in (True, False):
delay = 2.0
try:
with _open(request) as response:
return json.load(response)
except urllib.error.HTTPError as exc:
if exc.code == 404:
return None
if delay is None or not (exc.code >= 500 or exc.code == 429):
raise MergifyError(f"Mergify queue lookup failed with HTTP {exc.code}") from exc
except (OSError, http.client.IncompleteRead) as exc:
reason = exc.reason if isinstance(exc, urllib.error.URLError) else exc
if delay is None or isinstance(reason, ssl.SSLCertVerificationError):
raise MergifyError(f"Mergify queue transport failed: {reason}") from exc
except (json.JSONDecodeError, UnicodeDecodeError) as exc:
if delay is None:
raise MergifyError("Mergify queue lookup returned no valid JSON") from exc
_retry_sleep(delay)
wait = github.retry_after(exc.headers.get("Retry-After", "")) if exc.headers else None
delay = max(delay, wait or 0.0)
detail = f"Mergify queue lookup failed with HTTP {exc.code}" + (f"; Retry-After: {wait:g}s" if wait is not None else "")
transient = exc.code >= 500 or exc.code == 429 or (exc.code == 403 and wait is not None)
except (OSError, json.JSONDecodeError, UnicodeDecodeError, http.client.IncompleteRead) as exc:
detail, transient = _queue_read_failure(exc)
if not retry or not transient:
raise MergifyError(detail)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Queue read errors no longer keep the original exception

The old code raised MergifyError(...) from exc. The new code raises MergifyError(detail) after the except block has ended, so the error has neither __cause__ nor __context__. HTTP, socket and TLS tracebacks for a failed queue read are lost. Smallest fix: keep the caught exception (for example, error = exc in both handlers) and raise MergifyError(detail) from error at both raise sites (lines 125 and 127).

if not _wait_to_retry(delay, deadline):
raise MergifyError(f"{detail}; retry delay exceeds the wait budget")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Over-budget message mentions a wait budget that may not exist

Without a deadline (plain merge, status, or the hosted api_get callers), the 5s cap is internal. A 429 with Retry-After: 40 then reports "retry delay exceeds the wait budget", even though the user gave no wait budget. When deadline is None, consider wording such as "exceeds the unattended retry limit", so the explanation points the user to --wait as the remedy.

return None

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Removed blank line leaves only one blank line between top-level functions

The diff deletes one of the two blank lines between api_get and _unmet_conditions. Ruff doesn't fail on this because the configured rule set doesn't include E3. It's still inconsistent with the rest of the module. Fix: restore the second blank line.



def _unmet_conditions(node: object) -> tuple[str, ...]:
if not isinstance(node, dict) or node.get("match") is not False:
return ()
Expand All @@ -144,8 +159,8 @@ def _unmet_conditions(node: object) -> tuple[str, ...]:
return (label,) if isinstance(label, str) and label.isprintable() else ()


def membership(repo: str, number: int, queue: str) -> Membership | None:
data = api_get(repo, f"/merge-queue/pull/{number}")
def membership(repo: str, number: int, queue: str, deadline: float | None = None) -> Membership | None:
data = api_get(repo, f"/merge-queue/pull/{number}", deadline)
if data is None:
return None
try:
Expand Down Expand Up @@ -251,12 +266,12 @@ def construct_mapping(self, node, deep=False):
and isinstance(metadata, dict) and metadata.get("default_branch") == branch)


def configured(repo: str, branch: str, queue: str) -> bool:
def configured(repo: str, branch: str, queue: str, deadline: float | None = None) -> bool:
"""Require live queue identity and stable canonical speculative configuration."""
status_data = api_get(repo, f"/merge-queue/status?branch={quote(branch, safe='')}")
status_data = api_get(repo, f"/merge-queue/status?branch={quote(branch, safe='')}", deadline)
if status_data is None:
return False
rules_data = api_get(repo, "/queues/configuration")
rules_data = api_get(repo, "/queues/configuration", deadline)
if not isinstance(status_data, dict) or not isinstance(rules_data, dict):
return False
if not isinstance(status_data.get("batches"), list):
Expand Down
10 changes: 5 additions & 5 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -2623,7 +2623,7 @@ def source_queue_api(gh, monkeypatch):
})
vendor_calls = []

def get(_repo, path):
def get(_repo, path, *_):
vendor_calls.append(path)
return {
"/merge-queue/status?branch=main": {"batches": [], "mode": "serial"},
Expand Down Expand Up @@ -4367,7 +4367,7 @@ def membership(*_):

assert cli._wait_for_mergify(config, pr, 60 if confirmed else 360, confirmed=confirmed) == "e" * 40
assert clock.sleeps == ([30, 30] if confirmed else [30, 60, 120, 30])
assert configurations == [(REPO, "main", "main")] * (3 if confirmed else 4)
assert configurations == [(REPO, "main", "main", 60 if confirmed else 360)] * (3 if confirmed else 4)
assert reads_at_membership == ([1, 2, 3] if confirmed else [1, 4, 7, 10])
assert sum(c["argv"][:2] == detail for c in gh.calls) == (4 if confirmed else 9)
assert len(gh.calls) == (4 if confirmed else 12)
Expand Down Expand Up @@ -4418,9 +4418,8 @@ def test_mergify_wait_outcomes_preserve_unmerged_work(wt, repo, gh, capsys, monk
snapshots.extend((merge_json(head=head), merge_json(state="MERGED", head="f" * 40, sha="e" * 40)))
gh.append(f"api repos/{REPO}/pulls/7", *snapshots)
configurations = []

def configured(*_):
configurations.append(True)
def configured(*args):
configurations.append(args[-1])
if len(configurations) > 1:
if outcome == "config_error":
raise mergify.MergifyError("configuration HTTP 503")
Expand Down Expand Up @@ -4469,6 +4468,7 @@ def remove_worktree_then_poll(*args, **kwargs):
assert sum(c["argv"][:2] == PR_LIST_READ for c in gh.calls) == 1
assert sum(c["argv"][:2] == ["api", "graphql"] for c in gh.calls) == 2
assert requests == ([(REPO, 7, head, "main")] if outcome == "requested_head_changed" else [])
assert all(deadline == (250 if outcome == "timeout" else 0) for deadline in configurations)
if outcome.startswith("incompatible_"):
assert reads == [True] * (2 if landed else 1)
if not landed:
Expand Down
34 changes: 17 additions & 17 deletions tests/test_mergify.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ def test_dequeue_posts_to_documented_endpoint(request_log):
def queue_api(monkeypatch):
def github_config(text, *, default="main", changed=False, file_overrides=None, queues=True, inplace=True):
rows = [{"name": "main", "config": {"allow_inplace_checks": inplace}}] if queues else []
monkeypatch.setattr(mergify, "api_get", lambda _repo, suffix: (
monkeypatch.setattr(mergify, "api_get", lambda _repo, suffix, *_: (
{"batches": [], "mode": "serial"} if suffix.startswith("/merge-queue/status")
else {"configuration": rows}
))
Expand Down Expand Up @@ -214,17 +214,14 @@ def test_hosted_import_does_not_load_yaml():
assert result.returncode == 0, result.stderr


@pytest.mark.parametrize("failure,expected_sleeps", [
("http503", [2.0]), ("dropped_read", [2.0]), ("truncated", [2.0]),
("DNS lookup failed", [2.0, 5.0]),
(ssl.SSLCertVerificationError("certificate verification failed"), []),
@pytest.mark.parametrize("failure,status,budget,wait", [
("http", 503, None, 2), ("reset", None, None, 2), ("truncated", None, None, 2),
("http", 429, 100, 40), ("http", 429, None, None), ("http", 403, 20, None), ("http", 429, 20, None),
("DNS lookup failed", None, None, 2), (ssl.SSLCertVerificationError("certificate verification failed"), None, None, None),
])
def test_api_get_retries_and_classifies_failures(monkeypatch, failure, expected_sleeps):
def test_api_get_retries_and_classifies_failures(monkeypatch, failure, status, budget, wait):
calls, sleeps = [], []
body_errors = {
"dropped_read": ConnectionResetError(),
"truncated": http.client.IncompleteRead(b"{"),
}
body_errors = {"reset": ConnectionResetError(), "truncated": http.client.IncompleteRead(b"{")}

class Body(io.BytesIO):
def read(self, *args):
Expand All @@ -233,24 +230,27 @@ def read(self, *args):
return super().read(*args)

def fake_open(request):
calls.append(request.get_method())
if failure == "http503" and len(calls) == 1:
raise urllib.error.HTTPError(request.full_url, 503, "x", {}, None)
if failure != "http503" and failure not in body_errors:
calls.append((request.get_method(), sum(sleeps)))
if status in {403, 429} or (status == 503 and len(calls) == 1):
raise urllib.error.HTTPError(request.full_url, status, "x", {"Retry-After": "40"} if status < 500 else {}, None)
if not status and failure not in body_errors:
raise urllib.error.URLError(failure)
return Body(b"{}")

monkeypatch.setattr(mergify, "_open", fake_open)
monkeypatch.setattr(mergify, "_retry_sleep", sleeps.append)
monkeypatch.setattr(mergify, "_credential", lambda: "k")
if failure == "http503" or failure in body_errors:
if status in {403, 429}:
with pytest.raises(mergify.MergifyError, match="Retry-After: 40s" + ("; retry delay exceeds" if wait is None else "")):
mergify.api_get("acme/widgets", "/merge-queue/status", None if budget is None else mergify.time.monotonic() + budget)
elif status == 503 or failure in body_errors:
assert mergify.api_get("acme/widgets", "/merge-queue/status") == {}
assert calls == ["GET", "GET"]
else:
with pytest.raises(mergify.MergifyError, match="transport failed") as info:
mergify.api_get("acme/widgets", "/merge-queue/status")
assert str(failure) in str(info.value)
assert sleeps == expected_sleeps
assert calls == ([("GET", 0)] if wait is None else [("GET", 0), ("GET", wait)])
assert sleeps == ([] if wait is None else [wait])


@pytest.mark.parametrize("phase", ["headers", "body", "cleanup"])
Expand Down
Loading