From b7f1d94a428e680da126ac595d753028d497c418 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:34:19 +0100 Subject: [PATCH 1/4] Shorten waits at queue admission and source deadlines Architecture-Review: unchanged; polling cadence changes preserve the wait budget and exact-head checks. Co-Authored-By: Codex --- src/loopzero/cli.py | 14 ++++++--- tests/test_cli.py | 72 ++++++++++++++++++++++++++++++++++++++++----- 2 files changed, 75 insertions(+), 11 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 20b73319..3c474da7 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -1229,17 +1229,22 @@ 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, +) -> Iterator[None]: delay = WAIT_INTERVAL while True: + was_admitted = admitted is not None and admitted() yield # Observe immediately, including --wait=0. remaining = timeout - (time.monotonic() - 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 up to five seconds for the last bounded read. + _sleep(remaining - min(5.0, remaining / 10)) yield remaining = timeout - (time.monotonic() - started) if remaining > 0: @@ -1446,7 +1451,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 diff --git a/tests/test_cli.py b/tests/test_cli.py index dfc31abb..5c106e9e 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -2634,8 +2634,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") @@ -2678,7 +2678,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": @@ -2717,7 +2717,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 @@ -3164,6 +3164,36 @@ 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", [("ready", 300, 280), ("ready", 10, 8), ("merge", 10, 8)]) +def test_source_wait_observes_late_green(wt, gh, capsys, monkeypatch, head, command, timeout, green_at): + arm_approved_pr_with_check_result(gh, head, wt, "pending", isDraft=False) + clock = 0.0 + admitted = [] + + def advance(seconds): + nonlocal clock + clock += seconds + if clock >= green_at: + arm_check_runs(gh, head, [{"name": "checks", "status": "completed", "conclusion": "success"}]) + + 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) + 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] @@ -3188,7 +3218,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) @@ -4148,6 +4178,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) @@ -4256,9 +4314,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: From 32a225c7134c8c9964aecf67b30c3773b8804a13 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:44:04 +0100 Subject: [PATCH 2/4] Preserve final read time for subsecond waits Architecture-Review: unchanged; the bounded read retains its original deadline. Co-Authored-By: Codex --- src/loopzero/cli.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 3c474da7..1c73a987 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -1244,7 +1244,8 @@ def _poll_until( pause = delay * random.uniform(0.9, 1.0) if bounded and remaining <= pause: # Reserve up to five seconds for the last bounded read. - _sleep(remaining - min(5.0, remaining / 10)) + allowance = min(5.0, remaining / 2, max(0.5, remaining / 10)) + _sleep(remaining - allowance) yield remaining = timeout - (time.monotonic() - started) if remaining > 0: From f690e5d5bfad027aba52d6f50e4f656fc6ef448b Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:47:43 +0100 Subject: [PATCH 3/4] Reserve time for observed source-read latency Architecture-Review: unchanged; the adaptive allowance stays inside the existing source wait deadline. Co-Authored-By: Codex --- src/loopzero/cli.py | 11 ++++++++--- tests/test_cli.py | 14 ++++++++++++-- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 5d9b96a0..bfa10bf0 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -1234,18 +1234,23 @@ def _poll_until( started: float, timeout: float, *, bounded: bool = False, admitted: Callable[[], bool] | None = None, ) -> Iterator[None]: delay = WAIT_INTERVAL + longest_read = 0.0 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: - # Reserve up to five seconds for the last bounded read. - allowance = min(5.0, remaining / 2, max(0.5, remaining / 10)) + # 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)) _sleep(remaining - allowance) yield remaining = timeout - (time.monotonic() - started) diff --git a/tests/test_cli.py b/tests/test_cli.py index b27de23c..ebd219cf 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -3202,8 +3202,10 @@ 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", [("ready", 300, 280), ("ready", 10, 8), ("merge", 10, 8)]) -def test_source_wait_observes_late_green(wt, gh, capsys, monkeypatch, head, command, timeout, green_at): +@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), +]) +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 = 0.0 admitted = [] @@ -3214,6 +3216,13 @@ def advance(seconds): if clock >= green_at: arm_check_runs(gh, head, [{"name": "checks", "status": "completed", "conclusion": "success"}]) + view = github.pr_view + + 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 @@ -3222,6 +3231,7 @@ def merge(_repo, _number, _strategy, expected_head): monkeypatch.setattr(cli.random, "uniform", lambda *_: 0.95) monkeypatch.setattr(cli, "_sleep", advance) monkeypatch.setattr(github, "merge", merge) + monkeypatch.setattr(github, "pr_view", slow_view) gh.respond("api -X", "") code, out, err = run(capsys, command, f"--wait={timeout}") From b21c22bf53a6948236f3f4e44e581ff83b423a50 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:52:31 +0100 Subject: [PATCH 4/4] Include the first readiness read in the final poll allowance Architecture-Review: unchanged; readiness uses the original deadline and checks. Co-Authored-By: Codex --- src/loopzero/cli.py | 20 ++++++++++++++------ tests/test_cli.py | 10 +++++++++- 2 files changed, 23 insertions(+), 7 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index d4c6534c..d6622733 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -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) @@ -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 @@ -1254,9 +1256,10 @@ def _merge_check_hint(config: Config, pr: github.PR, readiness: github.Readiness 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 = 0.0 + longest_read = initial_read_time while True: was_admitted = admitted is not None and admitted() read_started = time.monotonic() @@ -1287,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: @@ -1302,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: @@ -1342,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 @@ -1363,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( @@ -1566,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() pr, readiness = _pr_readiness( wt, config, allow_merged=True, workflow_wait=args.wait is not None ) @@ -1577,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 diff --git a/tests/test_cli.py b/tests/test_cli.py index cb1cb240..86fdbaef 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -3233,10 +3233,11 @@ def test_merge_wait_times_out_on_pending_checks_with_exit_three( @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 = 0.0 + clock = -read_time admitted = [] def advance(seconds): @@ -3245,8 +3246,14 @@ def advance(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) @@ -3260,6 +3267,7 @@ def merge(_repo, _number, _strategy, expected_head): 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", "")