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
55f218b
Merge branch 'lean178/1502-safe-observation-retry' into lean178/1500-…
eowca Nov 26, 2026
44e7683
Expect one retry for idempotent finding resolution
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
20e1147
Reconcile draft activation before retrying
eowca Nov 26, 2026
feff835
Merge branch 'lean178/1502-safe-observation-retry' into lean178/1500-…
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
a5d06c5
Merge branch 'lean178/1502-safe-observation-retry' into lean178/1500-…
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
e0ae254
Merge branch 'lean178/1502-safe-observation-retry' into lean178/1500-…
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
96980d0
Apply the recovery deadline only to a repeated activation
eowca Nov 26, 2026
4122d5b
Merge branch 'lean178/1502-safe-observation-retry' into lean178/1500-…
eowca Nov 26, 2026
d630ae1
Merge remote-tracking branch 'origin/main' into lean178/1500-retry-dr…
eowca Nov 26, 2026
2beb1bc
Keep draft activation recovery inside ready timeout handling
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
104 changes: 79 additions & 25 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -1213,43 +1213,97 @@ def _cleanup(wt: Path, pr: github.PR) -> None:
print(f"warning: merged but worktree cleanup failed: {exc}{retry}", file=sys.stderr)


def _activate_draft(wt: Path, config: Config, pr: github.PR, deadline: float | None,
args: argparse.Namespace | None) -> None:
try:
github.mark_ready(config.repo, pr.number)

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: The first activation attempt can outlast the wait budget

The first github.mark_ready(config.repo, pr.number) call still uses the fixed 120 s timeout, while the retry is capped with _read_timeout(120). A hung first write can run past --wait, which guarantees the recovery path then fails on an expired deadline.

Capping the first attempt with min(120, deadline - now) whenever a deadline exists would make the two attempts consistent.

return
except (github.GhUnavailable, _proc.ProcTimeout) as exc:
if deadline is None:
raise
failure = f"Draft activation unconfirmed for PR #{pr.number}: {exc}"
retryable = isinstance(exc, _proc.ProcTimeout) or github._transient_error(exc.tail, False)

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: cli.py now depends on private GitHub retry helpers

_activate_draft calls github._transient_error, github._retry_pause and github._read_timeout, and re-derives the transient classification even though _gh already chose between GhUnavailable and GhError for the write. Checking isinstance(exc, GhUnavailable) again with _transient_error duplicates that classification and can drift from it (for example, a rate-limited GhUnavailable is treated differently here than in _gh).

Consider moving the observe-and-retry-once logic into a public helper in github.py, such as mark_ready(..., deadline) that returns whether a retry is allowed. The CLI would then not need these private helpers.

try:
_recover_draft_activation(wt, config, pr, deadline, args, retryable)
except github.ReadDeadline:
raise
except (CliError, github.GhError, _proc.ProcTimeout, OSError) as exc:
raise CliError(f"{failure} | recovery: {exc}") from exc


def _recover_draft_activation(wt: Path, config: Config, pr: github.PR, deadline: float,
args: argparse.Namespace | None, retryable: bool) -> None:
def observe() -> github.PR:
current = github.pr_view(config.repo, pr.number)
_verify_wait_snapshot(args, wt, config, pr.head_sha, current.head_sha)
if current.state != "OPEN" or current.number != pr.number:
raise CliError(f"no open PR #{pr.number} to activate")
return current

single_observation = args is not None and args.wait == 0
observation_deadline = time.monotonic() + 5 if single_observation else deadline

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: The hard-coded 5 s grace only applies to wait == 0, not to other expired budgets

wait == 0 gets a fresh 5-second observation window. A positive budget that has already run out (for example, --wait 1 after slow initial reads) gets no observation, because bounded_reads(deadline) raises right away on the first pr_view. The acceptance criterion ("observe the same PR and head after a transient activation failure") therefore holds only for that one literal value. The magic number also lets --wait 0 exceed what the user asked for.

Consider one rule for both cases, such as a single unbounded-but-short observation whenever the budget is already exhausted. At minimum, make the 5 s a named constant shared with the other single-observation timeouts.

with github.bounded_reads(observation_deadline, token=None):
if not observe().is_draft:
return
if single_observation:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

important: --wait 0 hides permanent activation failures as a resumable timeout

When single_observation is true and the PR is still a draft, the code raises ReadDeadline("draft activation is still unconfirmed") before it checks retryable. Take ready --wait 0 where mark_ready failed with a non-transient GhUnavailable, such as a 403/permission tail where _transient_error is False. cmd_ready catches the synthetic ReadDeadline at line 1296 and prints "timed out waiting for required checks … Run loopzero ready --wait to resume", then exits 3. The original failure (failure/exc) is dropped, and the user is told to retry something that will fail the same way every time. Before this change, the same path raised CliError("Draft activation unconfirmed …: <cause> | recovery: …") and exited 1.

The same instance exists for a positive budget: once the deadline has expired, observe()'s ReadDeadline is now re-raised at line 1228. A non-retryable activation failure is then reported as a plain timeout with exit 3 instead of the combined error.

Smallest fix: only turn the outcome into a timeout when the failure was retryable. Check if not retryable: raise CliError(...) before the single_observation raise. In _activate_draft, re-raise ReadDeadline only when retryable; otherwise keep wrapping it with failure so the cause is kept.

raise github.ReadDeadline(("gh", "pr", "ready"), "draft activation is still unconfirmed")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

important: merge --wait 0 now gets a bare ReadDeadline with no cause or timeout handling

_activate_draft is also called from _wait_for_checks (line 1464). It is reached by cmd_merge through _wait_with_deadline (line 1709). When timeout == 0, _wait_with_deadline (line 1389) calls _wait_for_checks outside its try/except github.ReadDeadline. So the new synthetic ReadDeadline for single_observation (and the re-raise at 1228) skips both the timeout printer and the failure wrapper and goes up to _run. There, as a GhError, it is printed as loopzero merge: draft activation is still unconfirmed and exits 1.

Compared with ready --wait 0, the same condition gives exit 3 plus a resume hint there. For merge, the exit code differs and the original mark_ready error text is lost. Only cmd_ready got the new except github.ReadDeadline wrapper. cmd_merge (the other caller of this defect class) was missed.

Fix: handle the ReadDeadline in one shared place for both callers. For example, move the timeout == 0 branch of _wait_with_deadline inside its existing try, or catch it there. Then drop the large try added around cmd_ready.

if not retryable or not github._retry_pause(github.RETRY_DELAY, 120):
raise CliError("retry is unavailable in this ready wait")
current = observe()
if not current.is_draft:
return
readiness = _readiness(wt, config, current, pr.head_sha, workflow_wait=True)
if not (readiness.ready or _draft_checks_waiting(config, current, readiness)):
raise CliError("; ".join(readiness.reasons))
github.mark_ready(config.repo, pr.number, github._read_timeout(120))


def cmd_ready(args: argparse.Namespace) -> int:
wt, config = _context(args, pin_checks=True)
pr, readiness = _pr_readiness(wt, config, workflow_wait=args.wait is not None)
assert readiness is not None
waiting = _draft_checks_waiting(config, pr, readiness)
kicked = bool(waiting)
started = time.monotonic()
if waiting:
github.mark_ready(config.repo, pr.number)
if args.wait is None:
pending = f"; {MERGEABILITY_PENDING}" if pr.mergeable == "UNKNOWN" else ""
print(f"marked ready; waiting for required checks: {', '.join(waiting)}{pending}; {NEXT_WAIT}")
return 3
print("marked ready; " + "; ".join(readiness.reasons))
if args.wait is not None and (
waiting or _pending_checks(config, pr, readiness, allow_skipped=not pr.is_draft)
):
waited = _wait_with_deadline(wt, config, pr, args.wait, kicked=kicked, started=started,
shown=readiness.reasons if kicked else (), args=args,
allow_skipped=True, initial=None if kicked else readiness)
if waited is None:
return 3
pr, readiness, kicked = waited
assert readiness is not None
if readiness.ready and pr.is_draft and not kicked:
github.mark_ready(config.repo, pr.number)
if args.wait is not None:
waited = _wait_with_deadline(wt, config, pr, args.wait, kicked=True, started=started,
args=args, allow_skipped=True)
deadline = None if args.wait is None else started + args.wait
Comment thread
eowca marked this conversation as resolved.
Resolved
try:

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: The broad try in cmd_ready adds a second timeout handler alongside _wait_with_deadline's

The whole body of cmd_ready is wrapped to catch ReadDeadline. _wait_with_deadline already converts ReadDeadline into a printed timeout plus None. This gives two places that print the timeout for one cause, and cmd_merge doesn't get the same behaviour (see the related finding). It's simpler and less likely to drift if ReadDeadline is caught only in _wait_with_deadline and the two direct _activate_draft calls in cmd_ready. Then the _report_ready split isn't needed just to keep the function readable.

if waiting:
_activate_draft(wt, config, pr, deadline, args)
if args.wait is None:
pending = f"; {MERGEABILITY_PENDING}" if pr.mergeable == "UNKNOWN" else ""
print(f"marked ready; waiting for required checks: {', '.join(waiting)}{pending}; {NEXT_WAIT}")
return 3
print("marked ready; " + "; ".join(readiness.reasons))
if args.wait is not None and (
waiting or _pending_checks(config, pr, readiness, allow_skipped=not pr.is_draft)
):
waited = _wait_with_deadline(wt, config, pr, args.wait, kicked=kicked, started=started,
shown=readiness.reasons if kicked else (), args=args,
allow_skipped=True, initial=None if kicked else readiness)
if waited is None:
return 3
pr, readiness, kicked = waited
assert readiness is not None
assert readiness is not None
if readiness.ready and pr.is_draft and not kicked:
_activate_draft(wt, config, pr, deadline, args)
if args.wait is not None:
waited = _wait_with_deadline(wt, config, pr, args.wait, kicked=True, started=started,
args=args, allow_skipped=True)
if waited is None:
return 3
pr, readiness, kicked = waited
assert readiness is not None
except github.ReadDeadline:
_print_check_wait_timeout(pr, args)
return 3
return _report_ready(pr, readiness, config, args.wait)


def _report_ready(pr: github.PR, readiness: github.Readiness, config: Config, wait: float | None) -> int:
for reason in _readiness_messages(pr, readiness):
print(f"not ready: {reason}")
if not readiness.ready:
if args.wait is None and _pending_checks(config, pr, readiness):
if wait is None and _pending_checks(config, pr, readiness):
print(NEXT_WAIT)
return 1
print(f"ready: {pr.url}")
Expand Down Expand Up @@ -1407,7 +1461,7 @@ def _wait_for_checks(
return current, None, kicked
readiness = _readiness(wt, config, current, pr.head_sha, workflow_wait=True)
if not kicked and _draft_checks_waiting(config, current, readiness):
github.mark_ready(config.repo, pr.number)
_activate_draft(wt, config, current, started + timeout, args)
print("marked ready; " + "; ".join(readiness.reasons))
return _wait_for_checks(wt, config, pr, timeout, kicked=True, started=started,
shown=readiness.reasons, args=args, bounded=bounded,
Expand Down
4 changes: 2 additions & 2 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -1386,8 +1386,8 @@ def readiness(
)


def mark_ready(repo: str, number: int) -> None:
_gh("pr", "ready", str(number), "--repo", repo)
def mark_ready(repo: str, number: int, timeout: float = 120) -> None:
_gh("pr", "ready", str(number), "--repo", repo, timeout=timeout)


_QUEUE_QUERY = (
Expand Down
40 changes: 20 additions & 20 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -2420,32 +2420,32 @@ def test_ready_wait_reports_initial_draft_blocker_once(wt, gh, capsys, monkeypat
]


@pytest.mark.parametrize("settles", [True, False])
def test_ready_wait_resumes_after_draft_transition(wt, gh, capsys, monkeypatch, head, settles):
@pytest.mark.parametrize("settles,fault", [(True, "interrupt"), (False, "interrupt"), (True, "lost"), (False, "lost_zero"), (True, "retry"), (False, "moved")])
def test_ready_wait_resumes_after_draft_transition(wt, gh, capsys, monkeypatch, head, settles, fault):
arm_approved_pr_with_check_result(gh, head, wt, "skipped", isDraft=True)
gh.respond("pr ready", "")
original_mark_ready = github.mark_ready

def interrupt_after_mark_ready(*args):
original_mark_ready(*args)
arm_pr(gh, head, isDraft=False)
raise KeyboardInterrupt

monkeypatch.setattr(github, "mark_ready", interrupt_after_mark_ready)
snapshots = ("skipped", "skipped", "skipped", "pending", "success") if settles else ("skipped",)
arm_check_progress(gh, head, *snapshots)
original, attempts, pauses = github.mark_ready, [], []
def activate(*args):
original(*args)
attempts.append(args)
if fault != "retry" or len(attempts) == 2:
arm_pr(gh, "b" * 40 if fault == "moved" else head, isDraft=False)
if len(attempts) == 1:
raise KeyboardInterrupt if fault == "interrupt" else github.ProcTimeout("lost activation reply")
monkeypatch.setattr(github, "mark_ready", activate)
monkeypatch.setattr(github, "_retry_sleep", pauses.append)
arm_check_progress(gh, head, *(("skipped", "skipped", "skipped", "pending", "success") if settles else ("skipped",)))
monkeypatch.setattr(cli, "WAIT_INTERVAL", 1.0)
monkeypatch.setattr(cli, "_sleep", lambda _: None)
wait = "--wait=30" if settles else "--wait=0"

assert run(capsys, "ready", wait)[0] == 130
wait = "--wait=30" if settles or fault == "moved" else "--wait=0"
if fault == "interrupt":
assert run(capsys, "ready", wait)[0] == 130
code, out, err = run(capsys, "ready", wait)

assert err == ""
assert code == (0 if settles else 3)
assert (code, "head changed" in err) == ((1, True) if fault == "moved" else (0 if settles else 3, False))
assert ("waiting: required check 'checks' is pending" in out) == settles
assert ("timed out waiting for required checks" in out) != settles
assert sum(c["argv"][:2] == ["pr", "ready"] for c in gh.calls) == 1
assert ("timed out waiting for required checks" in out) == (not settles and fault in {"interrupt", "lost_zero"})
assert sum(c["argv"][:2] == ["pr", "ready"] for c in gh.calls) == len(attempts) == (2 if fault == "retry" else 1)
assert pauses == ([5] if fault == "retry" else [])


@pytest.mark.parametrize("settled", ["success", "skipped"])
Expand Down
Loading