From 7119b10e59b17e45933270205a886a996faf3a71 Mon Sep 17 00:00:00 2001 From: adibarra <93070681+adibarra@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:27:29 -0600 Subject: [PATCH] fix(klaud): count running candidates toward the review backlog and requeue PRs main superseded The finished-PR backlog cap ignored claimed sessions and candidates taken earlier in the same wave, so a master config could overshoot it. Plan now counts family claims (once per candidate) and each wave take adds to its master config. Superseded-PR requeue compared the candidate image with every image the feed offered for the curve, so a newer image published by another key closed a validated PR. It now reads the PR's frozen baseline and requeues it only when main removed one of its keys or moved one to another image, which also closes PRs whose keys were retired. --- inferencex-e2e/infx/klaud/__main__.py | 76 +++++++++++-------- inferencex-e2e/infx/klaud/finished.py | 70 ++++++++++++----- .../infx/tests/klaud/test_klaud_finished.py | 67 ++++++++-------- .../infx/tests/klaud/test_klaud_planner.py | 36 +++++---- 4 files changed, 147 insertions(+), 102 deletions(-) diff --git a/inferencex-e2e/infx/klaud/__main__.py b/inferencex-e2e/infx/klaud/__main__.py index 45a1f31514..690323fe81 100644 --- a/inferencex-e2e/infx/klaud/__main__.py +++ b/inferencex-e2e/infx/klaud/__main__.py @@ -356,19 +356,18 @@ def family_prefixes(family: str) -> set[str]: return {identity(member)[:16] for member in {family, *key_families(family)}} -def offered_images( - items: list[dict], families: dict[tuple, dict[str, Family]] -) -> dict[str, set[str]]: - """Return the image keys ``choose`` builds candidate IDs from under each family prefix.""" - offered: dict[str, set[str]] = {} - for item in items: - if item["source-status"] != "baseline": - continue - image = identity(observation_key(item["source"])[-1])[:16] - for family in families.get(observation_key(item["source"]), {}): - for prefix in family_prefixes(family): - offered.setdefault(prefix, set()).add(image) - return offered +def master_images(root: Path) -> dict[str, str]: + """Return the normalized image of each master config key at ``root``, by single-key family.""" + from infx.config import project_root + from infx.matrix.validation import load_config_files + + root = project_root(root) + images = {} + for path in sorted((root / "configs").glob("*-master.yaml")): + source = path.relative_to(root).as_posix() + for key, entry in load_config_files([str(path)], validate=False).items(): + images[f"{source}:{key}"] = normalized_image(entry["image"]) + return images def hold(label: str | None, phase: str | None, cooldown_hours: int) -> timedelta: @@ -717,17 +716,22 @@ def __init__( ) -> None: """Start from ``headroom`` of clusters of ``size`` nodes, with ``backoff`` clusters. - ``backlog`` counts the open finished Klaud PRs of each master config. + ``backlog`` counts the finished and running Klaud candidates of each master config. """ self.headroom, self.size, self.backoff = dict(headroom), size, backoff - self.backlogged = {group for group, n in backlog.items() if n >= FINISHED_BACKLOG_CAP} + self.backlog = Counter(backlog) self.backed_off: set[str] = set() + @property + def backlogged(self) -> set[str]: + """The master configs with FINISHED_BACKLOG_CAP finished or running Klaud candidates.""" + return {group for group, n in self.backlog.items() if n >= FINISHED_BACKLOG_CAP} + def blocker(self, candidate: dict) -> str | None: """Return why the wave cannot take ``candidate`` now, or None. - That is "backlog" while its master config has FINISHED_BACKLOG_CAP finished PRs awaiting - review, then "backoff" or "capacity". + That is "backlog" while its master config has FINISHED_BACKLOG_CAP Klaud candidates + running or awaiting review, then "backoff" or "capacity". """ clusters = candidate["clusters"] if config_group(candidate["family"]) in self.backlogged: @@ -739,10 +743,11 @@ def blocker(self, candidate: dict) -> str | None: return None def take(self, candidate: dict) -> None: - """Reserve ``candidate``'s full sweep on each target cluster for the rest of the wave.""" + """Reserve ``candidate``'s full sweep and a backlog place for the rest of the wave.""" for cluster in candidate["clusters"]: self.headroom[cluster] -= min(candidate["sweep-node-demand"], self.size[cluster]) self.backed_off.update(self.backoff.intersection(candidate["clusters"])) + self.backlog[config_group(candidate["family"])] += 1 def klaud_pulls(pulls: list[dict]) -> list[dict]: @@ -759,12 +764,12 @@ def plan( are ordered toward idle clusters, cooled down by ``cooldown_hours`` and the recent-outcome holds, held while a maintainer recently closed their family's PR unless it was requeued, and capped at REVIEW_PER_SLOT per free slot plus REVIEW_MARGIN, at most - ``review_batch_size``. Candidates of master configs with FINISHED_BACKLOG_CAP finished PRs - awaiting review go last. Only open Klaud PRs are indexed. CLUSTER_STATE gives ``select`` - the claimed families' committed demand, the clusters under infrastructure backoff and the - finished PRs of each master config, and gives ``regenerate-producers`` this plan's headroom - and cluster sizes. Stale finished PRs whose family the feed now offers on another image are - first closed for requeue, which frees their families from the next wave on. + ``review_batch_size``. Candidates of master configs with FINISHED_BACKLOG_CAP Klaud + candidates running or awaiting review go last. Only open Klaud PRs are indexed. + CLUSTER_STATE gives ``select`` the claimed families' committed demand, the clusters under + infrastructure backoff and the finished and claimed candidates of each master config, and + gives ``regenerate-producers`` this plan's headroom and cluster sizes. Stale finished PRs + that main superseded are first closed for requeue and left out of the index. """ from . import claims from .finished import finished, requeue_superseded @@ -791,12 +796,10 @@ def plan( blocked = {candidate.family for owner in owners for candidate in owner.candidates} families = live_families(root) now = datetime.now(UTC) - requeue_superseded( - repository, - [pr for page in pulls for pr in page], - offered_images(items, families), - owners, - now, + superseded = set( + requeue_superseded( + repository, [pr for page in pulls for pr in page], master_images(root), owners, now + ) ) capacity = fetch_capacity(policy) or Capacity(idle={}, queued={}, size={}) committed = committed_demand(blocked, families, capacity.size) @@ -841,6 +844,7 @@ def plan( "finished": finished(repository, pr) is not None, } for pr in klaud_pulls([pr for page in pulls for pr in page]) + if pr["number"] not in superseded ] if candidates: for pr in open_prs: @@ -863,12 +867,19 @@ def plan( } ) pr["files-complete"] = sum(len(page) for page in pages) < 3000 + awaiting = {pr["branch"].removeprefix("klaud/auto-") for pr in open_prs if pr["finished"]} backlog = Counter( group for pr in open_prs if pr["finished"] for group in {config_group(name) for name in pr.get("files", [])} - {None} ) + backlog.update( + config_group(candidate.family) + for owner in owners + for candidate in owner.candidates + if candidate.id not in awaiting + ) wave = WaveCapacity({}, {}, set(), backlog) candidates = sorted(candidates, key=lambda candidate: wave.blocker(candidate) == "backlog") candidates = candidates[: min(review_batch_size, REVIEW_PER_SLOT * free_slots + REVIEW_MARGIN)] @@ -1361,7 +1372,8 @@ def select( the cap, and writes their context, ownership.json and selection.json under ``directory``. Those sessions are the larger of ``active_sessions``, counted by recovery before the review, and the ``running_sessions`` counted now. Selection stops if they are unreadable. - Candidates whose master config has FINISHED_BACKLOG_CAP finished PRs awaiting review wait. + Candidates whose master config has FINISHED_BACKLOG_CAP Klaud candidates running or awaiting + review, counting those this wave takes, wait. """ from . import claims, validation from .reporting import ( @@ -1565,7 +1577,7 @@ def select( summary += ( f" {len(backlog_deferred)} reviewed candidates wait because" f" {', '.join(sorted(wave.backlogged))} already have {FINISHED_BACKLOG_CAP} or more" - " finished Klaud PRs awaiting review." + " Klaud candidates running or awaiting review." ) if baseline_deferred: summary += f" {len(baseline_deferred)} candidates lacked a verifiable full baseline: " + ( diff --git a/inferencex-e2e/infx/klaud/finished.py b/inferencex-e2e/infx/klaud/finished.py index aa1c73161d..19bdef616b 100644 --- a/inferencex-e2e/infx/klaud/finished.py +++ b/inferencex-e2e/infx/klaud/finished.py @@ -19,9 +19,10 @@ from pathlib import Path from . import github +from .github import VerificationError from .lifecycle import BOT, CANDIDATE_ID, COMMITTER, owned_activity -from .models import REQUEUE_LABEL, Ownership, utc -from .reporting import translated +from .models import REQUEUE_LABEL, Ownership, family_keys, normalized_image, utc +from .reporting import baseline_from_body, translated CHANGELOG = "inferencex-e2e/perf-changelog.yaml" COMMITTER_EMAIL = "41898282+github-actions[bot]@users.noreply.github.com" @@ -230,29 +231,57 @@ def owned_candidates(repository: str, claimed: list[Ownership]) -> set[str]: return owned +def superseded(body: str, images: dict[str, str]) -> tuple[str, str] | None: + """Return why main superseded the finished PR with ``body`` in English and Chinese, or None. + + ``images`` maps each single-key family on main to its normalized image. The PR is + superseded once main removed a key of its frozen baseline's family or put one on another + image than the baseline froze. A body without a readable baseline is never superseded. + """ + try: + baseline = baseline_from_body(body) + except VerificationError: + return None + if baseline is None: + return None + source = baseline.family.split(":", 1)[0] + for key in family_keys(baseline.family): + current = images.get(f"{source}:{key}") + if current is None: + return ( + f"main removed config key `{key}` of this family", + f"main 已移除该配置族的配置键 `{key}`", + ) + frozen = baseline.keys[key].image if baseline.keys else baseline.image + if current != normalized_image(frozen): + return ( + f"main moved config key `{key}` of this family to another image", + f"main 已将该配置族的配置键 `{key}` 更新为其他镜像", + ) + return None + + def requeue_superseded( repository: str, pulls: list[dict], - offered: dict[str, set[str]], + images: dict[str, str], claimed: list[Ownership], now: datetime, ) -> list[int]: - """Close finished PRs older than STALE_DAYS whose family the feed offers on a newer image. + """Close finished PRs older than STALE_DAYS that main ``superseded``. - ``offered`` maps each family branch prefix to the image keys the planner would build its - candidates from. A finished PR started from an image its family no longer offers is - superseded, but still occupies the family. Closing it with REQUEUE_LABEL returns the family - to the pool. PRs a session still owns are skipped. Writes use ``$KLAUD_REQUEUE_TOKEN`` and - return the closed PR numbers. + ``images`` maps each single-key family on main to its normalized image. A superseded PR + still occupies its family and the review backlog, and closing it with REQUEUE_LABEL returns + the family to the pool. PRs a session still owns are skipped. Writes use + ``$KLAUD_REQUEUE_TOKEN`` and return the closed PR numbers. """ stale = [] for pull in pulls: candidate = finished(repository, pull) if not candidate or now - utc(pull["created_at"]) < timedelta(days=STALE_DAYS): continue - prefix, image = candidate.split("-") - if offered.get(prefix) and image not in offered[prefix]: - stale.append((pull, candidate)) + if reason := superseded(pull.get("body") or "", images): + stale.append((pull, candidate, reason)) if not stale: return [] try: @@ -261,18 +290,19 @@ def requeue_superseded( print(f"::warning::Klaud requeue skipped: ownership unavailable ({type(error).__name__})") return [] token = os.environ["KLAUD_REQUEUE_TOKEN"] - comment = translated( - f"**requeued** · Open for over {STALE_DAYS} days while the published baseline of this " - "family moved to a newer image. Closed with `klaud-requeue` so a new candidate can " - "refresh the family from its current image.", - f"**requeued** · 本 PR 已开放超过 {STALE_DAYS} 天,而该配置族已发布的基线已更新为" - "更新的镜像。已关闭并标记 `klaud-requeue`,新的候选可以基于当前镜像更新该配置族。", - ) closed = [] - for pull, candidate in stale: + for pull, candidate, (english, chinese) in stale: if candidate in owned: continue number = pull["number"] + comment = translated( + f"**requeued** · Open for over {STALE_DAYS} days while {english}, so its " + "validated sweep no longer matches main. Closed with `klaud-requeue` so a new " + "candidate can refresh the family from main.", + f"**requeued** · 本 PR 已开放超过 {STALE_DAYS} 天,期间 {chinese},其已验证的" + "测试已不再与 main 一致。已关闭并标记 `klaud-requeue`,新的候选可以基于 main 更新" + "该配置族。", + ) try: github.write( repository, diff --git a/inferencex-e2e/infx/tests/klaud/test_klaud_finished.py b/inferencex-e2e/infx/tests/klaud/test_klaud_finished.py index dfb215d472..e28483132c 100644 --- a/inferencex-e2e/infx/tests/klaud/test_klaud_finished.py +++ b/inferencex-e2e/infx/tests/klaud/test_klaud_finished.py @@ -3,9 +3,8 @@ import pytest -from infx.klaud import __main__ as klaud -from infx.klaud import finished, github -from infx.klaud.models import OwnedCandidate, Ownership, identity, utc +from infx.klaud import finished, github, reporting +from infx.klaud.models import OwnedCandidate, Ownership, utc from infx.tests.klaud.test_klaud_github import ended_session_sweep, recovery_pass from infx.workflows.validate_perf_changelog import parse_changelog @@ -181,39 +180,35 @@ def test_a_conflict_beyond_the_changelog_does_not_use_up_the_limit(tmp_path, mon assert git(remote, "rev-parse", f"refs/heads/{OLDER}") != heads[OLDER] -def test_offered_images_name_the_image_of_the_candidate_choose_builds(): - source = {"model": "m1", "hardware": "h100", "framework": "sglang", "precision": "fp8", - "spec_method": "none", "disagg": False, "benchmark_type": "agentic_traces", - "isl": None, "osl": None, "image": "example/sglang:v2", "date": "2026-10-20"} # fmt: skip - family = "configs/nvidia-master.yaml:agg,mtp" - families = {klaud.observation_key(source): { - family: klaud.Family(frozenset({"a"}), 1, 1, False)}} # fmt: skip - items = [{"source-status": "baseline", "source-id": "1", "source": source, - "benchmark-age-days": 0}] # fmt: skip +FAMILY = "configs/nvidia-master.yaml:agg" +SINGLE_POINT = "configs/nvidia-master.yaml:agg-c1" +OLD, NEW = "example/sglang:v1", "example/sglang:v2" - [candidate] = klaud.choose(items, {"a": 8}, set(), families) - prefix, image = candidate["id"].split("-") - offered = klaud.offered_images(items, families) - assert offered[prefix] == {image} - assert offered[identity("configs/nvidia-master.yaml:agg")[:16]] == {image} +def baseline_body(): + record = reporting.Baseline( + family=FAMILY, date="2026-10-19", image=OLD, + goal=reporting.Prose(en="Check the baseline.", zh="检查基线。"), + sources=["https://inferencex.semianalysis.com/api/v1/benchmarks"], points=[], + ) # fmt: skip + return "Summary\n" + reporting.baseline_marker(record) + "\n" -NEWER = {"1" * 16: {"3" * 16}} - - -@pytest.mark.parametrize(("created", "offered", "owned", "closed"), [ - pytest.param("2026-10-20T00:00:00Z", NEWER, False, True, id="stale-with-newer-image"), - pytest.param("2026-10-22T00:00:01Z", NEWER, False, False, id="fresh"), - pytest.param("2026-10-20T00:00:00Z", {"1" * 16: {"2" * 16, "3" * 16}}, False, False, - id="image-still-offered"), - pytest.param("2026-10-20T00:00:00Z", {}, False, False, id="family-not-offered"), - pytest.param("2026-10-20T00:00:00Z", NEWER, True, False, id="owned-by-a-session"), +@pytest.mark.parametrize(("created", "main", "owned", "reason"), [ + pytest.param("2026-10-20T00:00:00Z", {FAMILY: NEW, SINGLE_POINT: NEW}, False, + "main moved config key `agg` of this family to another image", + id="own-key-moved"), + pytest.param("2026-10-20T00:00:00Z", {SINGLE_POINT: OLD}, False, + "main removed config key `agg` of this family", id="own-key-removed"), + pytest.param("2026-10-20T00:00:00Z", {FAMILY: OLD, SINGLE_POINT: NEW}, False, None, + id="only-another-key-of-the-curve-moved"), + pytest.param("2026-10-22T00:00:01Z", {FAMILY: NEW}, False, None, id="fresh"), + pytest.param("2026-10-20T00:00:00Z", {FAMILY: NEW}, True, None, id="owned-by-a-session"), ]) # fmt: skip -def test_a_stale_finished_pr_whose_family_moved_to_a_newer_image_is_requeued( - monkeypatch, created, offered, owned, closed +def test_a_stale_finished_pr_that_main_superseded_is_requeued( + monkeypatch, created, main, owned, reason ): - pull = {**finished_pr("c" * 40), "created_at": created} + pull = {**finished_pr("c" * 40), "created_at": created, "body": baseline_body()} writes = [] monkeypatch.setenv("KLAUD_REQUEUE_TOKEN", "pat-fixture") monkeypatch.setattr( @@ -244,20 +239,22 @@ def test_a_stale_finished_pr_whose_family_moved_to_a_newer_image_is_requeued( numbers = finished.requeue_superseded( REPOSITORY, [pull, {**pull, "number": 8, "draft": True}], - offered, + main, claimed if owned else [], utc("2026-10-27T00:00:00Z"), ) - assert numbers == ([7] if closed else []) + assert numbers == ([7] if reason else []) assert [(method, path, token) for method, path, _, token in writes] == ([ ("POST", "issues/7/labels", "pat-fixture"), ("POST", "issues/7/comments", "pat-fixture"), ("PATCH", "pulls/7", "pat-fixture"), - ] if closed else []) # fmt: skip - if closed: + ] if reason else []) # fmt: skip + if reason: assert writes[0][2] == {"labels": ["klaud-requeue"]} - assert writes[1][2]["body"].startswith("**requeued** · ") + assert writes[1][2]["body"].startswith( + f"**requeued** · Open for over 5 days while {reason}," + ) assert writes[2][2] == {"state": "closed"} diff --git a/inferencex-e2e/infx/tests/klaud/test_klaud_planner.py b/inferencex-e2e/infx/tests/klaud/test_klaud_planner.py index 94aae83e74..e4d65bddea 100644 --- a/inferencex-e2e/infx/tests/klaud/test_klaud_planner.py +++ b/inferencex-e2e/infx/tests/klaud/test_klaud_planner.py @@ -587,23 +587,24 @@ def test_select_counts_the_sessions_running_when_it_selects( assert f"Selection stopped: {reason}." in summary -def test_select_defers_candidates_of_a_master_config_with_a_finished_pr_backlog( +def test_select_defers_candidates_of_a_master_config_whose_backlog_the_wave_fills( tmp_path, monkeypatch ): - capacity = api.Capacity(idle={"a": 4, "b": 4}, queued={}, size={"a": 4, "b": 4}) + capacity = api.Capacity(idle=dict.fromkeys("abc", 4), queued={}, size=dict.fromkeys("abc", 4)) busy = wave_context("busy", ["a"]) - quiet = {**wave_context("quiet", ["b"]), "family": "configs/amd-master.yaml:quiet"} + quiet, later = ({**wave_context(name, [cluster]), "family": f"configs/amd-master.yaml:{name}"} + for name, cluster in (("quiet", "b"), ("later", "c"))) # fmt: skip selection, summary = select_wave( - tmp_path, monkeypatch, [busy, quiet], lambda _policy: capacity, + tmp_path, monkeypatch, [busy, quiet, later], lambda _policy: capacity, backlog={"nvidia-master.yaml": 8, "amd-master.yaml": 7}) # fmt: skip assert selection["candidates"] == [quiet["id"]] - assert selection["backlog-deferred-candidates"] == [busy["id"]] - assert selection["backlogged-configs"] == ["nvidia-master.yaml"] + assert selection["backlog-deferred-candidates"] == [busy["id"], later["id"]] + assert selection["backlogged-configs"] == ["amd-master.yaml", "nvidia-master.yaml"] assert ( - "1 reviewed candidates wait because nvidia-master.yaml already have 8 or more" - " finished Klaud PRs awaiting review." + "2 reviewed candidates wait because amd-master.yaml, nvidia-master.yaml already have 8 or" + " more Klaud candidates running or awaiting review." ) in summary @@ -700,7 +701,8 @@ def read(_repository, path, paginate=False): ("idle", 2, True), ("dated", 2, False)] # fmt: skip assert json.loads((directory / klaud.CLUSTER_STATE).read_text()) == { "committed-demand": {"big": 20}, "infra-backoff": ["a"], "headroom": {"a": 2, "b": 6}, - "size": {"a": 8, "b": 8, "big": 20}, "finished-backlog": {}} # fmt: skip + "size": {"a": 8, "b": 8, "big": 20}, + "finished-backlog": {"nvidia-master.yaml": 1}} # fmt: skip def open_pull(number, finished): @@ -713,10 +715,10 @@ def open_pull(number, finished): def plan_curves(tmp_path, monkeypatch, curves, *, history=None, closed=None, pulls=(), batch=64, - slots=5): # fmt: skip + slots=5, owners=()): # fmt: skip """Plan ``curves`` that all serve one feed observation; return their order and cluster state. - ``pulls`` lists (number, master config, finished) of open Klaud PRs. + ``pulls`` lists (number, master config, finished) of open Klaud PRs, ``owners`` the claims. """ source = feed_source("m1", "example/sglang:v1") target = klaud.Family(frozenset({"a"}), 1, 1, False) @@ -741,7 +743,7 @@ def read(_repository, path, paginate=False): monkeypatch.setattr(klaud, "github_read", read) monkeypatch.setattr(klaud, "live_families", lambda _root: { klaud.observation_key(source): dict.fromkeys(curves, target)}) # fmt: skip - monkeypatch.setattr(claims, "family_owners", lambda _repository: []) + monkeypatch.setattr(claims, "family_owners", lambda _repository: list(owners)) monkeypatch.setattr(klaud, "fetch_capacity", lambda _policy: api.Capacity( idle={"a": 8}, queued={}, size={"a": 8})) # fmt: skip monkeypatch.setattr(klaud, "maintainer_closed_families", lambda _repository, _now: ( @@ -782,14 +784,18 @@ def test_plan_retries_a_requeued_candidate_despite_its_maintainer_close(tmp_path assert planned == [requeued] -def test_plan_counts_finished_prs_per_master_config_and_reviews_backlogged_ones_last( +def test_plan_counts_finished_and_claimed_candidates_per_master_config_and_orders_backlog_last( tmp_path, monkeypatch ): busy, quiet = "configs/nvidia-master.yaml:busy", "configs/amd-master.yaml:quiet" - pulls = [*((number, "nvidia-master.yaml", True) for number in range(8)), + pulls = [*((number, "nvidia-master.yaml", True) for number in range(6)), (8, "nvidia-master.yaml", False), (9, "amd-master.yaml", True)] # fmt: skip + claimed = [OwnedCandidate(id=f"{number:016x}-{'0' * 16}", + family=f"configs/nvidia-master.yaml:running-{number}", base="a" * 40) + for number in (0, 10, 11)] # fmt: skip - planned, state = plan_curves(tmp_path, monkeypatch, [busy, quiet], pulls=pulls) + planned, state = plan_curves(tmp_path, monkeypatch, [busy, quiet], pulls=pulls, + owners=[Ownership(run_id=42, candidates=claimed)]) # fmt: skip assert planned == [quiet, busy] assert state["finished-backlog"] == {"nvidia-master.yaml": 8, "amd-master.yaml": 1}