Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
3eca5fd
Keep hosted eligibility pending during GitHub outages
eowca Nov 26, 2026
d26ca8b
Keep hosted eligibility pending during GitHub outages
eowca Nov 26, 2026
9d9d15f
Retry safe GitHub observations once within their budget
eowca Nov 26, 2026
44e7683
Expect one retry for idempotent finding resolution
eowca Nov 26, 2026
ec8ed7a
Merge branch 'lean178/1502-safe-observation-retry' into lean178/1499-…
eowca Nov 26, 2026
9b2fdeb
Keep hosted refresh failures observable before pending publication
eowca Nov 26, 2026
71a4432
Merge remote-tracking branch 'origin/main' into lean178/1497-eligibil…
eowca Nov 26, 2026
71a8ff7
Preserve genuine missing-object failures during candidate fetch
eowca Nov 26, 2026
67df7d4
Merge branch 'lean178/1497-eligibility-outages' into lean178/1502-saf…
eowca Nov 26, 2026
da45c03
Merge remote-tracking branch 'origin/main' into lean178/1502-safe-obs…
eowca Nov 26, 2026
d2614ec
Honor Retry-After on Mergify queue observations
eowca Nov 26, 2026
9bd1845
Merge branch 'lean178/1502-safe-observation-retry' into lean178/1499-…
eowca Nov 26, 2026
b60a084
Verify the same deadline reaches every queue observation
eowca Nov 26, 2026
0234af9
Recognize HTTP outages in Git fetch diagnostics
eowca Nov 26, 2026
2cd175e
Merge branch 'lean178/1497-eligibility-outages' into lean178/1502-saf…
eowca Nov 26, 2026
33cb637
Merge branch 'lean178/1502-safe-observation-retry' into lean178/1499-…
eowca Nov 26, 2026
1aae039
Keep hosted eligibility pending during GitHub outages
eowca Nov 26, 2026
0c68daf
Keep hosted refresh failures observable before pending publication
eowca Nov 26, 2026
b945542
Preserve genuine missing-object failures during candidate fetch
eowca Nov 26, 2026
db8a695
Recognize HTTP outages in Git fetch diagnostics
eowca Nov 26, 2026
6c65b6a
Keep retry timing scoped to its follow-up change
eowca Nov 26, 2026
251719a
Merge branch 'lean178/1497-eligibility-outages-v2' into lean178/1502-…
eowca Nov 26, 2026
e780406
Merge remote-tracking branch 'origin/main' into lean178/1502-safe-obs…
eowca Nov 26, 2026
0349474
Merge branch 'lean178/1502-safe-observation-retry' into lean178/1499-…
eowca Nov 26, 2026
1e7cd89
Merge remote-tracking branch 'origin/main' into lean178/1502-safe-obs…
eowca Nov 26, 2026
c1d8bb7
Preserve the trusted-publisher fixture on the retry branch
eowca Nov 26, 2026
6ac05fd
Keep GitHub write timeouts outside read deadlines
eowca Nov 26, 2026
ff316b1
Merge branch 'lean178/1502-safe-observation-retry' into lean178/1499-…
eowca Nov 26, 2026
fe2382a
Merge remote-tracking branch 'origin/main' into lean178/1499-mergify-…
eowca Nov 26, 2026
f52c6f7
Keep Mergify backoff within readiness and default budgets
eowca Nov 26, 2026
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 @@ -352,8 +352,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
Comment thread
eowca marked this conversation as resolved.
Resolved
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
24 changes: 13 additions & 11 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ def _decide_kind(markers: list[Marker], head: str) -> tuple[str, str | None]:

def _readiness(
wt: Path, config: Config, pr: github.PR, head: str, reviews: list[dict] | None = None,
*, workflow_wait: bool = False, announce_receipt: bool = False,
*, workflow_wait: bool = False, announce_receipt: bool = False, mergify_deadline: float | None = None,
) -> github.Readiness:
if hold := github.merge_hold(pr.number, pr.labels):
return github.Readiness(False, (hold,))
Expand Down Expand Up @@ -316,7 +316,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 @@ -1184,7 +1184,8 @@ def _load_review(wt: Path, head: str, kind: str) -> ReviewResult:


def _pr_readiness(
wt: Path, config: Config, *, allow_merged: bool = False, workflow_wait: bool = False
wt: Path, config: Config, *, 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)."""
branch, head = worktree.branch(wt), worktree.head(wt)
Expand All @@ -1194,7 +1195,7 @@ def _pr_readiness(
if pr.state == "MERGED":
return pr, None
return pr, _readiness(wt, config, pr, head, workflow_wait=workflow_wait,
announce_receipt=True)
announce_receipt=True, mergify_deadline=mergify_deadline)


CLEANUP_RETRY = "; fix the cause, then rerun `loopzero merge` in this worktree to finish cleanup"
Expand Down Expand Up @@ -1405,7 +1406,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):
github.mark_ready(config.repo, pr.number)
print("marked ready; " + "; ".join(readiness.reasons))
Expand Down Expand Up @@ -1561,9 +1563,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 @@ -1601,7 +1603,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 @@ -1642,11 +1644,11 @@ 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
pr, readiness = _pr_readiness(
wt, config, 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, 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):
Expand Down
18 changes: 12 additions & 6 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -334,15 +334,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
40 changes: 26 additions & 14 deletions src/loopzero/mergify.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,15 @@ def _open(request: urllib.request.Request):
raise MergifyError("Mergify API request has an invalid URL or header") from None


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 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")
Expand All @@ -91,22 +99,26 @@ def api_get(repo: str, suffix: str) -> object | None:
headers={"Accept": "application/json", "User-Agent": "loopzero",
"Authorization": f"Bearer {_credential()}"},
)
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, ValueError, http.client.IncompleteRead) 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"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, ValueError, http.client.IncompleteRead):
detail, transient = "transport or invalid JSON response", True
if not retry or not transient:
raise MergifyError(f"Mergify queue lookup failed with {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: Lost exception cause, and a missing blank line before _unmet_conditions

The MergifyError is now raised outside the except block, so the original HTTPError or OSError is no longer chained (from exc was removed). That makes transport failures harder to diagnose. Keep a reference to the caught exception (error = exc) and use raise MergifyError(...) from error, unless the chain was dropped on purpose to keep sensitive data out of diagnostics. If so, add a comment saying that. Separately, the diff removes one of the two blank lines before def _unmet_conditions (PEP 8 / flake8 E302).

if not _wait_to_retry(delay, deadline):
Comment thread
eowca marked this conversation as resolved.
Resolved
raise MergifyError(f"Mergify queue lookup failed with {detail}; retry delay exceeds the wait budget")
return None


def _unmet_conditions(node: object) -> tuple[str, ...]:
if not isinstance(node, dict) or node.get("match") is not False:
return ()
Expand All @@ -117,8 +129,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 @@ -187,12 +199,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 @@ -2496,7 +2496,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 @@ -4336,7 +4336,7 @@ def configured(*args):

assert cli._wait_for_mergify(config, pr, 60, confirmed=True) == "e" * 40
assert sleeps == [30, 30]
assert configurations == [(REPO, "main", "main")] * 3
assert configurations == [(REPO, "main", "main", 60)] * 3
assert reads_at_membership == [1, 2, 3]
assert [c["argv"][:2] for c in gh.calls] == [detail] * 4

Expand Down Expand Up @@ -4382,8 +4382,8 @@ def test_mergify_wait_outcomes_preserve_unmerged_work(wt, repo, gh, capsys, monk
gh.append(f"api repos/{REPO}/pulls/7", merge_json(state='OPEN', head=head),
merge_json(state='MERGED', head='f' * 40, sha='e' * 40))
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 @@ -4430,7 +4430,7 @@ def remove_worktree_then_poll(*args):
assert sleeps == ([30, 60, 120, 40] if jitter == 1 else [27, 54, 108, 61])
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 requests == ([(REPO, 7, head, "main")] if outcome == "requested_head_changed" else []) and all(deadline == (250 if outcome == "timeout" else 0) for deadline in configurations)
if outcome in {"merged", "already_merged", "worktree_removed"}:
assert code == 0 and "e" * 40 in out and not wt.exists(), err
if outcome == "worktree_removed":
Expand Down
40 changes: 20 additions & 20 deletions tests/test_mergify.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def open_(request): # a transient failure must not repeat the write

@pytest.fixture
def queue_api(monkeypatch):
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": [{"name": "main", "config": {"allow_inplace_checks": True}}]}
))
Expand Down Expand Up @@ -154,7 +154,7 @@ def test_configured_still_requires_vendor_queue_identity(queue_api, monkeypatch)

def test_legacy_false_does_not_license_single_check_source_updates(queue_api, monkeypatch):
queue_api(SAFE_CONFIG.replace("checks: 3", "checks: 1"))
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": [{"name": "main", "config": {"allow_inplace_checks": False}}]}
))
Expand Down Expand Up @@ -229,24 +229,24 @@ def test_hosted_import_does_not_load_yaml():
assert result.returncode == 0, result.stderr


@pytest.mark.parametrize("failure", ["http503", "dropped_read", "truncated"])
def test_api_get_retries_transient_reads(monkeypatch, failure):
calls = []

class Body(io.BytesIO):
def read(self, *args):
if len(calls) == 1 and failure != "http503": # body read fails once
raise {"dropped_read": ConnectionResetError(), "truncated": mergify.http.client.IncompleteRead(b"{")}[failure]
return super().read(*args)

@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)])
def test_api_get_retries_transient_reads(monkeypatch, failure, status, budget, wait):
calls, sleeps = [], []
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)
return Body(b"{}")

calls.append((request.get_method(), sum(sleeps)))
if status in {403, 429} or len(calls) == 1:
if status:
raise urllib.error.HTTPError(request.full_url, status, "x", {"Retry-After": "40"} if status < 500 else {}, None)
raise ConnectionResetError() if failure == "reset" else mergify.http.client.IncompleteRead(b"{")
return io.BytesIO(b"{}")
monkeypatch.setattr(mergify, "_open", fake_open)
monkeypatch.setattr(mergify, "_retry_sleep", lambda _: None)
monkeypatch.setattr(mergify, "_retry_sleep", sleeps.append)
monkeypatch.setattr(mergify, "_credential", lambda: "k")
assert mergify.api_get("acme/widgets", "/merge-queue/status") == {}
assert calls == ["GET", "GET"]
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)
else:
assert mergify.api_get("acme/widgets", "/merge-queue/status") == {}
assert calls == ([("GET", 0)] if wait is None else [("GET", 0), ("GET", wait)])