Skip to content

Commit 0f15344

Browse files
authored
fix(klaud): count running candidates toward the review backlog and requeue PRs main superseded (#5051)
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.
1 parent 29f3168 commit 0f15344

4 files changed

Lines changed: 147 additions & 102 deletions

File tree

‎inferencex-e2e/infx/klaud/__main__.py‎

Lines changed: 44 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -357,19 +357,18 @@ def family_prefixes(family: str) -> set[str]:
357357
return {identity(member)[:16] for member in {family, *key_families(family)}}
358358

359359

360-
def offered_images(
361-
items: list[dict], families: dict[tuple, dict[str, Family]]
362-
) -> dict[str, set[str]]:
363-
"""Return the image keys ``choose`` builds candidate IDs from under each family prefix."""
364-
offered: dict[str, set[str]] = {}
365-
for item in items:
366-
if item["source-status"] != "baseline":
367-
continue
368-
image = identity(observation_key(item["source"])[-1])[:16]
369-
for family in families.get(observation_key(item["source"]), {}):
370-
for prefix in family_prefixes(family):
371-
offered.setdefault(prefix, set()).add(image)
372-
return offered
360+
def master_images(root: Path) -> dict[str, str]:
361+
"""Return the normalized image of each master config key at ``root``, by single-key family."""
362+
from infx.config import project_root
363+
from infx.matrix.validation import load_config_files
364+
365+
root = project_root(root)
366+
images = {}
367+
for path in sorted((root / "configs").glob("*-master.yaml")):
368+
source = path.relative_to(root).as_posix()
369+
for key, entry in load_config_files([str(path)], validate=False).items():
370+
images[f"{source}:{key}"] = normalized_image(entry["image"])
371+
return images
373372

374373

375374
def hold(
@@ -748,17 +747,22 @@ def __init__(
748747
) -> None:
749748
"""Start from ``headroom`` of clusters of ``size`` nodes, with ``backoff`` clusters.
750749
751-
``backlog`` counts the open finished Klaud PRs of each master config.
750+
``backlog`` counts the finished and running Klaud candidates of each master config.
752751
"""
753752
self.headroom, self.size, self.backoff = dict(headroom), size, backoff
754-
self.backlogged = {group for group, n in backlog.items() if n >= FINISHED_BACKLOG_CAP}
753+
self.backlog = Counter(backlog)
755754
self.backed_off: set[str] = set()
756755

756+
@property
757+
def backlogged(self) -> set[str]:
758+
"""The master configs with FINISHED_BACKLOG_CAP finished or running Klaud candidates."""
759+
return {group for group, n in self.backlog.items() if n >= FINISHED_BACKLOG_CAP}
760+
757761
def blocker(self, candidate: dict) -> str | None:
758762
"""Return why the wave cannot take ``candidate`` now, or None.
759763
760-
That is "backlog" while its master config has FINISHED_BACKLOG_CAP finished PRs awaiting
761-
review, then "backoff" or "capacity".
764+
That is "backlog" while its master config has FINISHED_BACKLOG_CAP Klaud candidates
765+
running or awaiting review, then "backoff" or "capacity".
762766
"""
763767
clusters = candidate["clusters"]
764768
if config_group(candidate["family"]) in self.backlogged:
@@ -770,10 +774,11 @@ def blocker(self, candidate: dict) -> str | None:
770774
return None
771775

772776
def take(self, candidate: dict) -> None:
773-
"""Reserve ``candidate``'s full sweep on each target cluster for the rest of the wave."""
777+
"""Reserve ``candidate``'s full sweep and a backlog place for the rest of the wave."""
774778
for cluster in candidate["clusters"]:
775779
self.headroom[cluster] -= min(candidate["sweep-node-demand"], self.size[cluster])
776780
self.backed_off.update(self.backoff.intersection(candidate["clusters"]))
781+
self.backlog[config_group(candidate["family"])] += 1
777782

778783

779784
def klaud_pulls(pulls: list[dict]) -> list[dict]:
@@ -790,12 +795,12 @@ def plan(
790795
are ordered toward idle clusters, cooled down by ``cooldown_hours`` and the recent-outcome
791796
holds, held while a maintainer recently closed their family's PR unless it was requeued,
792797
and capped at REVIEW_PER_SLOT per free slot plus REVIEW_MARGIN, at most
793-
``review_batch_size``. Candidates of master configs with FINISHED_BACKLOG_CAP finished PRs
794-
awaiting review go last. Only open Klaud PRs are indexed. CLUSTER_STATE gives ``select``
795-
the claimed families' committed demand, the clusters under infrastructure backoff and the
796-
finished PRs of each master config, and gives ``regenerate-producers`` this plan's headroom
797-
and cluster sizes. Stale finished PRs whose family the feed now offers on another image are
798-
first closed for requeue, which frees their families from the next wave on.
798+
``review_batch_size``. Candidates of master configs with FINISHED_BACKLOG_CAP Klaud
799+
candidates running or awaiting review go last. Only open Klaud PRs are indexed.
800+
CLUSTER_STATE gives ``select`` the claimed families' committed demand, the clusters under
801+
infrastructure backoff and the finished and claimed candidates of each master config, and
802+
gives ``regenerate-producers`` this plan's headroom and cluster sizes. Stale finished PRs
803+
that main superseded are first closed for requeue and left out of the index.
799804
"""
800805
from . import claims
801806
from .finished import finished, requeue_superseded
@@ -822,12 +827,10 @@ def plan(
822827
blocked = {candidate.family for owner in owners for candidate in owner.candidates}
823828
families = live_families(root)
824829
now = datetime.now(UTC)
825-
requeue_superseded(
826-
repository,
827-
[pr for page in pulls for pr in page],
828-
offered_images(items, families),
829-
owners,
830-
now,
830+
superseded = set(
831+
requeue_superseded(
832+
repository, [pr for page in pulls for pr in page], master_images(root), owners, now
833+
)
831834
)
832835
capacity = fetch_capacity(policy) or Capacity(idle={}, queued={}, size={})
833836
committed = committed_demand(blocked, families, capacity.size)
@@ -872,6 +875,7 @@ def plan(
872875
"finished": finished(repository, pr) is not None,
873876
}
874877
for pr in klaud_pulls([pr for page in pulls for pr in page])
878+
if pr["number"] not in superseded
875879
]
876880
if candidates:
877881
for pr in open_prs:
@@ -894,12 +898,19 @@ def plan(
894898
}
895899
)
896900
pr["files-complete"] = sum(len(page) for page in pages) < 3000
901+
awaiting = {pr["branch"].removeprefix("klaud/auto-") for pr in open_prs if pr["finished"]}
897902
backlog = Counter(
898903
group
899904
for pr in open_prs
900905
if pr["finished"]
901906
for group in {config_group(name) for name in pr.get("files", [])} - {None}
902907
)
908+
backlog.update(
909+
config_group(candidate.family)
910+
for owner in owners
911+
for candidate in owner.candidates
912+
if candidate.id not in awaiting
913+
)
903914
wave = WaveCapacity({}, {}, set(), backlog)
904915
candidates = sorted(candidates, key=lambda candidate: wave.blocker(candidate) == "backlog")
905916
candidates = candidates[: min(review_batch_size, REVIEW_PER_SLOT * free_slots + REVIEW_MARGIN)]
@@ -1392,7 +1403,8 @@ def select(
13921403
the cap, and writes their context, ownership.json and selection.json under ``directory``.
13931404
Those sessions are the larger of ``active_sessions``, counted by recovery before the
13941405
review, and the ``running_sessions`` counted now. Selection stops if they are unreadable.
1395-
Candidates whose master config has FINISHED_BACKLOG_CAP finished PRs awaiting review wait.
1406+
Candidates whose master config has FINISHED_BACKLOG_CAP Klaud candidates running or awaiting
1407+
review, counting those this wave takes, wait.
13961408
"""
13971409
from . import claims, validation
13981410
from .reporting import (
@@ -1596,7 +1608,7 @@ def select(
15961608
summary += (
15971609
f" {len(backlog_deferred)} reviewed candidates wait because"
15981610
f" {', '.join(sorted(wave.backlogged))} already have {FINISHED_BACKLOG_CAP} or more"
1599-
" finished Klaud PRs awaiting review."
1611+
" Klaud candidates running or awaiting review."
16001612
)
16011613
if baseline_deferred:
16021614
summary += f" {len(baseline_deferred)} candidates lacked a verifiable full baseline: " + (

‎inferencex-e2e/infx/klaud/finished.py‎

Lines changed: 50 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,10 @@
1919
from pathlib import Path
2020

2121
from . import github
22+
from .github import VerificationError
2223
from .lifecycle import BOT, CANDIDATE_ID, COMMITTER, owned_activity
23-
from .models import REQUEUE_LABEL, Ownership, utc
24-
from .reporting import translated
24+
from .models import REQUEUE_LABEL, Ownership, family_keys, normalized_image, utc
25+
from .reporting import baseline_from_body, translated
2526

2627
CHANGELOG = "inferencex-e2e/perf-changelog.yaml"
2728
COMMITTER_EMAIL = "41898282+github-actions[bot]@users.noreply.github.com"
@@ -230,29 +231,57 @@ def owned_candidates(repository: str, claimed: list[Ownership]) -> set[str]:
230231
return owned
231232

232233

234+
def superseded(body: str, images: dict[str, str]) -> tuple[str, str] | None:
235+
"""Return why main superseded the finished PR with ``body`` in English and Chinese, or None.
236+
237+
``images`` maps each single-key family on main to its normalized image. The PR is
238+
superseded once main removed a key of its frozen baseline's family or put one on another
239+
image than the baseline froze. A body without a readable baseline is never superseded.
240+
"""
241+
try:
242+
baseline = baseline_from_body(body)
243+
except VerificationError:
244+
return None
245+
if baseline is None:
246+
return None
247+
source = baseline.family.split(":", 1)[0]
248+
for key in family_keys(baseline.family):
249+
current = images.get(f"{source}:{key}")
250+
if current is None:
251+
return (
252+
f"main removed config key `{key}` of this family",
253+
f"main 已移除该配置族的配置键 `{key}`",
254+
)
255+
frozen = baseline.keys[key].image if baseline.keys else baseline.image
256+
if current != normalized_image(frozen):
257+
return (
258+
f"main moved config key `{key}` of this family to another image",
259+
f"main 已将该配置族的配置键 `{key}` 更新为其他镜像",
260+
)
261+
return None
262+
263+
233264
def requeue_superseded(
234265
repository: str,
235266
pulls: list[dict],
236-
offered: dict[str, set[str]],
267+
images: dict[str, str],
237268
claimed: list[Ownership],
238269
now: datetime,
239270
) -> list[int]:
240-
"""Close finished PRs older than STALE_DAYS whose family the feed offers on a newer image.
271+
"""Close finished PRs older than STALE_DAYS that main ``superseded``.
241272
242-
``offered`` maps each family branch prefix to the image keys the planner would build its
243-
candidates from. A finished PR started from an image its family no longer offers is
244-
superseded, but still occupies the family. Closing it with REQUEUE_LABEL returns the family
245-
to the pool. PRs a session still owns are skipped. Writes use ``$KLAUD_REQUEUE_TOKEN`` and
246-
return the closed PR numbers.
273+
``images`` maps each single-key family on main to its normalized image. A superseded PR
274+
still occupies its family and the review backlog, and closing it with REQUEUE_LABEL returns
275+
the family to the pool. PRs a session still owns are skipped. Writes use
276+
``$KLAUD_REQUEUE_TOKEN`` and return the closed PR numbers.
247277
"""
248278
stale = []
249279
for pull in pulls:
250280
candidate = finished(repository, pull)
251281
if not candidate or now - utc(pull["created_at"]) < timedelta(days=STALE_DAYS):
252282
continue
253-
prefix, image = candidate.split("-")
254-
if offered.get(prefix) and image not in offered[prefix]:
255-
stale.append((pull, candidate))
283+
if reason := superseded(pull.get("body") or "", images):
284+
stale.append((pull, candidate, reason))
256285
if not stale:
257286
return []
258287
try:
@@ -261,18 +290,19 @@ def requeue_superseded(
261290
print(f"::warning::Klaud requeue skipped: ownership unavailable ({type(error).__name__})")
262291
return []
263292
token = os.environ["KLAUD_REQUEUE_TOKEN"]
264-
comment = translated(
265-
f"**requeued** · Open for over {STALE_DAYS} days while the published baseline of this "
266-
"family moved to a newer image. Closed with `klaud-requeue` so a new candidate can "
267-
"refresh the family from its current image.",
268-
f"**requeued** · 本 PR 已开放超过 {STALE_DAYS} 天,而该配置族已发布的基线已更新为"
269-
"更新的镜像。已关闭并标记 `klaud-requeue`,新的候选可以基于当前镜像更新该配置族。",
270-
)
271293
closed = []
272-
for pull, candidate in stale:
294+
for pull, candidate, (english, chinese) in stale:
273295
if candidate in owned:
274296
continue
275297
number = pull["number"]
298+
comment = translated(
299+
f"**requeued** · Open for over {STALE_DAYS} days while {english}, so its "
300+
"validated sweep no longer matches main. Closed with `klaud-requeue` so a new "
301+
"candidate can refresh the family from main.",
302+
f"**requeued** · 本 PR 已开放超过 {STALE_DAYS} 天,期间 {chinese},其已验证的"
303+
"测试已不再与 main 一致。已关闭并标记 `klaud-requeue`,新的候选可以基于 main 更新"
304+
"该配置族。",
305+
)
276306
try:
277307
github.write(
278308
repository,

‎inferencex-e2e/infx/tests/klaud/test_klaud_finished.py‎

Lines changed: 32 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,8 @@
33

44
import pytest
55

6-
from infx.klaud import __main__ as klaud
7-
from infx.klaud import finished, github
8-
from infx.klaud.models import OwnedCandidate, Ownership, identity, utc
6+
from infx.klaud import finished, github, reporting
7+
from infx.klaud.models import OwnedCandidate, Ownership, utc
98
from infx.tests.klaud.test_klaud_github import ended_session_sweep, recovery_pass
109
from infx.workflows.validate_perf_changelog import parse_changelog
1110

@@ -181,39 +180,35 @@ def test_a_conflict_beyond_the_changelog_does_not_use_up_the_limit(tmp_path, mon
181180
assert git(remote, "rev-parse", f"refs/heads/{OLDER}") != heads[OLDER]
182181

183182

184-
def test_offered_images_name_the_image_of_the_candidate_choose_builds():
185-
source = {"model": "m1", "hardware": "h100", "framework": "sglang", "precision": "fp8",
186-
"spec_method": "none", "disagg": False, "benchmark_type": "agentic_traces",
187-
"isl": None, "osl": None, "image": "example/sglang:v2", "date": "2026-10-20"} # fmt: skip
188-
family = "configs/nvidia-master.yaml:agg,mtp"
189-
families = {klaud.observation_key(source): {
190-
family: klaud.Family(frozenset({"a"}), 1, 1, False)}} # fmt: skip
191-
items = [{"source-status": "baseline", "source-id": "1", "source": source,
192-
"benchmark-age-days": 0}] # fmt: skip
183+
FAMILY = "configs/nvidia-master.yaml:agg"
184+
SINGLE_POINT = "configs/nvidia-master.yaml:agg-c1"
185+
OLD, NEW = "example/sglang:v1", "example/sglang:v2"
193186

194-
[candidate] = klaud.choose(items, {"a": 8}, set(), families)
195-
prefix, image = candidate["id"].split("-")
196187

197-
offered = klaud.offered_images(items, families)
198-
assert offered[prefix] == {image}
199-
assert offered[identity("configs/nvidia-master.yaml:agg")[:16]] == {image}
188+
def baseline_body():
189+
record = reporting.Baseline(
190+
family=FAMILY, date="2026-10-19", image=OLD,
191+
goal=reporting.Prose(en="Check the baseline.", zh="检查基线。"),
192+
sources=["https://inferencex.semianalysis.com/api/v1/benchmarks"], points=[],
193+
) # fmt: skip
194+
return "Summary\n" + reporting.baseline_marker(record) + "\n"
200195

201196

202-
NEWER = {"1" * 16: {"3" * 16}}
203-
204-
205-
@pytest.mark.parametrize(("created", "offered", "owned", "closed"), [
206-
pytest.param("2026-10-20T00:00:00Z", NEWER, False, True, id="stale-with-newer-image"),
207-
pytest.param("2026-10-22T00:00:01Z", NEWER, False, False, id="fresh"),
208-
pytest.param("2026-10-20T00:00:00Z", {"1" * 16: {"2" * 16, "3" * 16}}, False, False,
209-
id="image-still-offered"),
210-
pytest.param("2026-10-20T00:00:00Z", {}, False, False, id="family-not-offered"),
211-
pytest.param("2026-10-20T00:00:00Z", NEWER, True, False, id="owned-by-a-session"),
197+
@pytest.mark.parametrize(("created", "main", "owned", "reason"), [
198+
pytest.param("2026-10-20T00:00:00Z", {FAMILY: NEW, SINGLE_POINT: NEW}, False,
199+
"main moved config key `agg` of this family to another image",
200+
id="own-key-moved"),
201+
pytest.param("2026-10-20T00:00:00Z", {SINGLE_POINT: OLD}, False,
202+
"main removed config key `agg` of this family", id="own-key-removed"),
203+
pytest.param("2026-10-20T00:00:00Z", {FAMILY: OLD, SINGLE_POINT: NEW}, False, None,
204+
id="only-another-key-of-the-curve-moved"),
205+
pytest.param("2026-10-22T00:00:01Z", {FAMILY: NEW}, False, None, id="fresh"),
206+
pytest.param("2026-10-20T00:00:00Z", {FAMILY: NEW}, True, None, id="owned-by-a-session"),
212207
]) # fmt: skip
213-
def test_a_stale_finished_pr_whose_family_moved_to_a_newer_image_is_requeued(
214-
monkeypatch, created, offered, owned, closed
208+
def test_a_stale_finished_pr_that_main_superseded_is_requeued(
209+
monkeypatch, created, main, owned, reason
215210
):
216-
pull = {**finished_pr("c" * 40), "created_at": created}
211+
pull = {**finished_pr("c" * 40), "created_at": created, "body": baseline_body()}
217212
writes = []
218213
monkeypatch.setenv("KLAUD_REQUEUE_TOKEN", "pat-fixture")
219214
monkeypatch.setattr(
@@ -244,20 +239,22 @@ def test_a_stale_finished_pr_whose_family_moved_to_a_newer_image_is_requeued(
244239
numbers = finished.requeue_superseded(
245240
REPOSITORY,
246241
[pull, {**pull, "number": 8, "draft": True}],
247-
offered,
242+
main,
248243
claimed if owned else [],
249244
utc("2026-10-27T00:00:00Z"),
250245
)
251246

252-
assert numbers == ([7] if closed else [])
247+
assert numbers == ([7] if reason else [])
253248
assert [(method, path, token) for method, path, _, token in writes] == ([
254249
("POST", "issues/7/labels", "pat-fixture"),
255250
("POST", "issues/7/comments", "pat-fixture"),
256251
("PATCH", "pulls/7", "pat-fixture"),
257-
] if closed else []) # fmt: skip
258-
if closed:
252+
] if reason else []) # fmt: skip
253+
if reason:
259254
assert writes[0][2] == {"labels": ["klaud-requeue"]}
260-
assert writes[1][2]["body"].startswith("**requeued** · ")
255+
assert writes[1][2]["body"].startswith(
256+
f"**requeued** · Open for over 5 days while {reason},"
257+
)
261258
assert writes[2][2] == {"state": "closed"}
262259

263260

0 commit comments

Comments
 (0)