Skip to content
Merged
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
76 changes: 44 additions & 32 deletions inferencex-e2e/infx/klaud/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand All @@ -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]:
Expand All @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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:
Expand All @@ -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)]
Comment on lines 883 to 885

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 (optional) Free slots can sit idle in a wave because the plan reviews mostly candidates that select will then defer for backlog. plan still sorts and truncates with a static backlog. select now adds each taken candidate to the backlog. A config one place below FINISHED_BACKLOG_CAP still sorts first, so the truncated batch can be filled with its candidates. Candidates from configs with room fall outside the batch. Fix: order the candidates in plan by modelling in-wave takes the way select does. Each config gets at most FINISHED_BACKLOG_CAP - backlog[group] candidates ahead of the backlog ones. [also at: inferencex-e2e/infx/klaud/main.py:750 - After this change, producers can be prepared for candidates that select later defers for backlog. Candidates select would take can then be left without producers.]

Why this was flagged

In this pass nvidia-master.yaml has 7 counted backlog entries (the PR description says it now starts at or near the cap). free_slots is 2, so the batch at __main__.py:885 is min(review_batch_size, 3*2+4) = 10. The sort at __main__.py:884 calls wave.blocker with the static Counter, so nvidia candidates are not marked "backlog" and keep their idle-first and cooldown order. nvidia-master has about 145 keys against 47 for amd, so the 10 reviewed candidates can all be nvidia. In select, wave.take (__main__.py:750) moves nvidia to 8 after the first pick, and the other nine land in backlog-deferred-candidates. The second slot stays empty even though amd-master candidates were available but cut off by the truncation. On the base branch the static count let select take both nvidia candidates (the overshoot this PR fixes). Plan and select used the same rule, so no reviewed batch was wasted that way. Nothing in plan models the new in-wave increment.

Verification: Trigger: one master config is one below FINISHED_BACKLOG_CAP (8) at plan time, with 2 or more free slots. plan sorts against a static Counter and truncates (main.py:883-885). In select, wave.take(candidate) now adds to the backlog (line 750), so later candidates from that config are deferred and a slot stays empty for the wave. On the base, both slots filled, but by going over the cap.

Expand Down Expand Up @@ -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 (
Expand Down Expand Up @@ -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: " + (
Expand Down
70 changes: 50 additions & 20 deletions inferencex-e2e/infx/klaud/finished.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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:
Comment on lines +241 to +245

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 (optional) A stale finished PR whose body baseline is missing or no longer parses is now never requeued, so it keeps its family and backlog place until someone closes it by hand. superseded returns None on VerificationError or a missing record, and logs nothing. The base requeued such PRs from the candidate ID alone. Fix: when the baseline cannot be read, emit a ::warning:: naming the PR, and fall back to the base's image check, which reads pull["head"]["ref"] and needs no body. This keeps unreadable-baseline PRs from being skipped forever.

Why this was flagged

The condition is a finished Klaud PR older than STALE_DAYS (5) whose body holds no klaud-baseline-record:v1 line, or holds one that the current strict Baseline contract rejects. A body with no record can still finish, because baseline_for (reporting.py:844-851) also accepts a baseline stored in a comment. requeue_superseded (finished.py:283) calls superseded(pull.get("body") or "", images). That catches the VerificationError at finished.py:241-243, or gets None at :244-245, and returns None without any log. The PR is then never closed, even after main removes its key or moves its image. On the base, requeue_superseded decided from the candidate ID prefix and image (candidate.split("-") against offered) and needed no body. No safeguard covers them: no other step requeues finished PRs, and nothing warns about them.

Verification: superseded (finished.py, new) does except VerificationError: return None and if baseline is None: return None, and prints nothing. requeue_superseded now only appends to stale when superseded(pull.get("body") or "", images) returns a reason, so these PRs are skipped with no ::warning::. The base decided from the head ref alone.

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:
Expand All @@ -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,
Expand Down
67 changes: 32 additions & 35 deletions inferencex-e2e/infx/tests/klaud/test_klaud_finished.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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"}


Expand Down
Loading
Loading