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
22 changes: 17 additions & 5 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -1230,17 +1230,28 @@ 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
longest_read = 0.0
while True:
was_admitted = admitted is not None and admitted()
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: 'Read latency' counts the whole consumer loop body

read_started/now measure all the time the generator is suspended. That includes work after the read in the consumer: mark_ready, printing, _readiness workflow lookups, and in the Mergify loop, mark_confirmed. That is fine as a conservative estimate. Because the value is a lifetime maximum, though, one slow outlier, such as a retried API call, keeps the final allowance high, up to remaining/2, for the rest of the wait. This is bounded and safe. Consider renaming it to something like longest_pass so the comment matches what is measured. You could also note that longest_read is unused when bounded=False.

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))
_sleep(remaining - allowance)
yield
remaining = timeout - (time.monotonic() - started)
if remaining > 0:
Expand Down Expand Up @@ -1447,7 +1458,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)

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 polls variable is unnecessary

polls = _poll_until(...) followed by for _ in polls: adds a name that is used only once. Inline it as for _ in _poll_until(started, timeout, admitted=lambda: confirmed): to keep the diff smaller. The lambda reads the confirmed local through its closure, so the reassignment at line 1469 is still seen and the admission reset behaves as intended.

for _ in polls:
sha = _landed(config, pr, closed)
if sha:
return sha
Expand Down
82 changes: 75 additions & 7 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -2672,8 +2672,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 @@ -2716,7 +2716,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 @@ -2755,7 +2755,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 @@ -3202,6 +3202,46 @@ 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", [

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: Test-line size budget still fails the full check

scripts/size_budget.sh sets TESTS_CAP=13500. It fails when the tree is over that cap and has grown against its base. The tests in this worktree currently count 13,503 lines, and this delta adds about 11 lines to test_source_wait_observes_late_green. The task notes also say the gate blocks the full check (13,522 against 13,500). As things stand, loopzero check and CI fail on the size gate, so this does not meet acceptance. Smallest fix: drop the separate read_time=0 handling and the view = github.pr_view alias by wrapping the original inline, keep the parametrize table on fewer lines, or trim redundant lines elsewhere in this test so the total is back at or under 13,500. Don't raise the cap to get around it.

("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 = []

def advance(seconds):
nonlocal clock
clock += 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

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(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 @@ -3226,7 +3266,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 @@ -4186,6 +4226,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 @@ -4294,9 +4362,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