Skip to content
Closed
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
40 changes: 30 additions & 10 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -1172,6 +1172,7 @@ def _cleanup(wt: Path, pr: github.PR) -> None:

def cmd_ready(args: argparse.Namespace) -> int:
wt, config = _context(args, pin_checks=True)
read_started = time.monotonic()
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)
Expand All @@ -1189,7 +1190,8 @@ def cmd_ready(args: argparse.Namespace) -> int:
):
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)
allow_skipped=True, initial=None if kicked else readiness,
initial_read_time=started - read_started)
if waited is None:
return 3
pr, readiness, kicked = waited
Expand Down Expand Up @@ -1252,17 +1254,29 @@ def _merge_check_hint(config: Config, pr: github.PR, readiness: github.Readiness
return ""


def _poll_until(started: float, timeout: float, *, bounded: bool = False) -> Iterator[None]:
def _poll_until(
started: float, timeout: float, *, bounded: bool = False, admitted: Callable[[], bool] | None = None,
initial_read_time: float = 0.0,
) -> Iterator[None]:
delay = WAIT_INTERVAL
longest_read = initial_read_time
while True:
was_admitted = admitted is not None and admitted()
read_started = time.monotonic()
yield # Observe immediately, including --wait=0.
remaining = timeout - (time.monotonic() - started)
now = time.monotonic()
longest_read = max(longest_read, now - read_started)
remaining = timeout - (now - started)
if remaining <= 0:
return
if admitted is not None and not was_admitted and admitted():
delay = WAIT_INTERVAL
pause = delay * random.uniform(0.9, 1.0)
if bounded and remaining <= pause:
# Leave part of the final interval for the last observation to complete.
_sleep(remaining / 2)
# Reserve time for a complete readiness pass based on observed latency.
baseline = min(5.0, max(0.5, remaining / 10))
allowance = min(remaining / 2, max(baseline, 2 * longest_read))
Comment thread
eowca marked this conversation as resolved.
Resolved
_sleep(remaining - allowance)
yield
remaining = timeout - (time.monotonic() - started)
if remaining > 0:
Expand All @@ -1276,6 +1290,7 @@ def _wait_with_deadline(
wt: Path, config: Config, pr: github.PR, timeout: float, *, kicked: bool,
started: float | None = None, shown: tuple[str, ...] = (), args: argparse.Namespace,
allow_merged: bool = False, allow_skipped: bool = False, initial: github.Readiness | None = None,
initial_read_time: float = 0.0,
) -> tuple[github.PR, github.Readiness | None, bool] | None:
started = time.monotonic() if started is None else started
if timeout == 0:
Expand All @@ -1291,7 +1306,8 @@ def _wait_with_deadline(
with github.bounded_reads(deadline, token=None, retry=True):
waited = _wait_for_checks(wt, config, pr, timeout, kicked=kicked, started=started,
shown=shown, args=args, bounded=True, allow_merged=allow_merged,
allow_skipped=allow_skipped, initial=initial)
allow_skipped=allow_skipped, initial=initial,
initial_read_time=initial_read_time)
reported_timeout = waited is None
except github.ReadDeadline:
if not reported_timeout:
Expand Down Expand Up @@ -1331,13 +1347,14 @@ def _wait_for_checks(
started: float | None = None, shown: tuple[str, ...] = (),
args: argparse.Namespace | None = None, bounded: bool = False, allow_merged: bool = False,
allow_skipped: bool = False, initial: github.Readiness | None = None,
initial_read_time: float = 0.0,
) -> tuple[github.PR, github.Readiness | None, bool] | None:
"""Poll the same head until it settles, omitting readiness for an allowed merge."""
grace_started = time.monotonic()
started = grace_started if started is None else started
current = pr
stale_notice = False
for _ in _poll_until(started, timeout, bounded=bounded):
for _ in _poll_until(started, timeout, bounded=bounded, initial_read_time=initial_read_time):
if initial is not None:
readiness = initial
initial = None
Expand All @@ -1352,7 +1369,7 @@ def _wait_for_checks(
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,
allow_merged=allow_merged)
allow_merged=allow_merged, initial_read_time=initial_read_time)
if kicked and readiness.ready and timeout > 0 and time.monotonic() - started > timeout:
break # A post-transition read cannot grant success beyond the original deadline.
pending = _pending_checks(
Expand Down Expand Up @@ -1469,7 +1486,8 @@ def _wait_for_mergify(
state = None
deferred_landing_read = False
print(f"PR #{pr.number} following Mergify queue {queue}; head {pr.head_sha[:12]}; waiting up to {timeout:g}s")
for _ in _poll_until(started, timeout):
polls = _poll_until(started, timeout, admitted=lambda: confirmed)
for _ in polls:
sha = _landed(config, pr, closed)
if sha:
return sha
Expand Down Expand Up @@ -1554,6 +1572,7 @@ 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()

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: Seeded read latency covers more work than a poll read

initial_read_time times all of _pr_readiness. That covers worktree.branch/worktree.head, pr_for_branch, _require_pushed and _readiness(..., announce_receipt=True). A later poll read in _wait_for_checks only runs pr_view, _verify_wait_snapshot and _readiness. When the initial read is the slowest read, 2 * longest_read can overstate the final-read cost. The allowance is capped at remaining / 2, so the final observation still happens. It may just come earlier than it needs to, which works against the late-green goal. If this matters in practice, a cheap fix is to start the timer just before the _readiness call inside _pr_readiness, for example by returning the elapsed time from there. Otherwise, a one-line comment saying the seed is a deliberate overestimate would explain the trade-off. In the test, the initial read path does not call github.pr_view, so the -read_time clock offset correctly charges exactly one read_time to the initial read.

pr, readiness = _pr_readiness(
wt, config, allow_merged=True, workflow_wait=args.wait is not None
)
Expand All @@ -1565,7 +1584,8 @@ def cmd_merge(args: argparse.Namespace) -> int:
# 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)
args=args, allow_merged=True, initial=readiness,
initial_read_time=started - read_started)
if waited is None:
return 3
pr, readiness, _ = waited
Expand Down
90 changes: 83 additions & 7 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -2692,8 +2692,8 @@ def advance(seconds):

assert (code, err) == (expected, "")
assert "waiting: required check 'checks' is cancelled" in out
assert sleeps == ([30.0, 5.0, 5.0] if replacement == "pending" else
[30.0, 5.0] if initial_pending else [30.0])
assert sleeps == ([30.0, 9.0, 1.0] if replacement == "pending" else
[30.0, 9.0] if initial_pending else [30.0])
assert out.endswith(f"ready: {URL}\n" if expected == 0 else
"not ready: required check 'checks' is failure\n" if expected == 1 else
f"timed out waiting for required checks on {head[:12]}\n")
Expand Down Expand Up @@ -2736,7 +2736,7 @@ def late_read(*args, **kwargs):
code, out, err = run(capsys, "ready", "--wait=40")

assert code == (1 if after in {"head_move", "blocker", "cancelled"} else 3)
assert sleeps == ([30.0, 5.0, 5.0] if after == "pending" else [30.0])
assert sleeps == ([30.0, 9.0, 1.0] if after == "pending" else [30.0])
assert "ready: https" not in out
assert ("PR head changed while waiting" in err) == (after == "head_move")
if after == "cancelled":
Expand Down Expand Up @@ -2775,7 +2775,7 @@ def advance(seconds):

assert (code, err) == (0 if run_appears else 3, "")
assert marked_at == [210.0]
assert sleeps == [30.0, 60.0, 120.0, 30.0] + ([] if run_appears else [30.0, 30.0])
assert sleeps == [30.0, 60.0, 120.0, 30.0] + ([] if run_appears else [55.0, 5.0])
assert out.endswith(f"ready: {URL}\n" if run_appears else
f"timed out waiting for required checks on {head[:12]}\n")
assert sum(c["argv"][:2] == ["pr", "ready"] for c in gh.calls) == 1
Expand Down Expand Up @@ -3231,6 +3231,54 @@ def test_merge_wait_times_out_on_pending_checks_with_exit_three(
assert wt.exists() and all(c["argv"][:2] != ["pr", "merge"] for c in gh.calls)


@pytest.mark.parametrize("command,timeout,green_at,read_time", [
("ready", 300, 280, 0), ("ready", 300, 280, 7), ("ready", 10, 8, 0), ("merge", 10, 8, 0),
("ready", 10, 8, 1.25), ("merge", 10, 8, 1.25),
])
def test_source_wait_observes_late_green(wt, gh, capsys, monkeypatch, head, command, timeout, green_at, read_time):
arm_approved_pr_with_check_result(gh, head, wt, "pending", isDraft=False)
clock = -read_time
admitted = []

def advance(seconds):
nonlocal clock
clock += seconds
if clock >= green_at:
arm_check_runs(gh, head, [{"name": "checks", "status": "completed", "conclusion": "success"}])

initial_read = cli._pr_readiness
view = github.pr_view

def slow_initial_read(*args, **kwargs):
result = initial_read(*args, **kwargs)
advance(read_time)
return result

def slow_view(*args, **kwargs):
if clock:
advance(read_time)
return view(*args, **kwargs)

def merge(_repo, _number, _strategy, expected_head):
admitted.append(expected_head)
return "c" * 40

monkeypatch.setattr(cli.time, "monotonic", lambda: clock)
monkeypatch.setattr(cli.random, "uniform", lambda *_: 0.95)
monkeypatch.setattr(cli, "_sleep", advance)
monkeypatch.setattr(github, "merge", merge)
monkeypatch.setattr(cli, "_pr_readiness", slow_initial_read)
monkeypatch.setattr(github, "pr_view", slow_view)
gh.respond("api -X", "")

code, out, err = run(capsys, command, f"--wait={timeout}")

assert (code, err) == (0, "")
assert green_at <= clock < timeout
assert admitted == ([head] if command == "merge" else [])
assert out.splitlines()[-1] == ("c" * 40 if command == "merge" else f"ready: {URL}")


def test_merge_wait_bounds_slow_source_check_read(wt, gh, capsys, monkeypatch, head, replay_gh):
arm_approved_pr_with_check_result(gh, head, wt, "pending", isDraft=False)
clock = [1000.0]
Expand All @@ -3255,7 +3303,7 @@ def slow_check(argv, *, timeout, **kwargs):
code, out, err = run(capsys, "merge", "--wait=16")

assert (code, err) == (3, "")
assert budgets == pytest.approx([8.0])
assert budgets == pytest.approx([1.6])
assert f"timed out waiting for required checks on {head[:12]}" in out
assert all(c["argv"][:2] != ["pr", "merge"] for c in gh.calls)

Expand Down Expand Up @@ -4215,6 +4263,34 @@ def test_ready_pins_review_publishers_to_base(wt, gh, capsys, publisher, head):
assert run(capsys, "ready")[0] == (0 if publisher == LOGIN else 1)


def test_mergify_landing_backoff_restarts_on_admission(wt, gh, monkeypatch):
commit_mergify_configuration(wt)
head = head_of(wt)
config = cli.config_mod.load_trusted(wt)
pr = github.PR(7, URL, head, "main", False, "OPEN", "MERGEABLE")
detail = f"api repos/{REPO}/pulls/7"
gh.respond(detail, merge_json(state="OPEN", head=head))
clock = 0.0
confirmations = []

def advance(seconds):
nonlocal clock
clock += seconds
if clock >= 201:
gh.respond(detail, merge_json(state="MERGED", head=head, sha="e" * 40))

monkeypatch.setattr(cli.time, "monotonic", lambda: clock)
monkeypatch.setattr(cli.random, "uniform", lambda *_: 0.95)
monkeypatch.setattr(cli, "_sleep", advance)
monkeypatch.setattr(mergify, "configured", lambda *_: True)
monkeypatch.setattr(mergify, "membership", lambda *_: mergify.Membership() if clock >= 195 else None)
monkeypatch.setattr(mergify, "mark_confirmed", lambda *_: confirmations.append(clock))

assert cli._wait_for_mergify(config, pr, 360, confirmed=False) == "e" * 40
assert confirmations == [199.5]
assert clock == 228


def test_mergify_confirmed_wait_reads_pr_once_per_steady_poll(wt, gh, monkeypatch):
commit_mergify_configuration(wt)
head = head_of(wt)
Expand Down Expand Up @@ -4323,9 +4399,9 @@ def membership(*_):
if outcome == "worktree_removed":
poll_until = cli._poll_until

def remove_worktree_then_poll(*args):
def remove_worktree_then_poll(*args, **kwargs):
git(repo, "worktree", "remove", "--force", str(wt))
return poll_until(*args)
return poll_until(*args, **kwargs)

monkeypatch.setattr(cli, "_poll_until", remove_worktree_then_poll)
try:
Expand Down
Loading