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
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
bump: patch
---

### Fixed

- post-merge-demotion-alert.yml warns when the suite judge (`babysit_postmerge.py --judge-run`) exits 2 to 4, with the judge's `error` from its JSON output, and still files the demotion as before. Before, the record was filed with nothing saying the judge had failed.
- A dispatched red run is treated as recovered, and files nothing, only when the newer green run's head descends from the red SHA and is on the `main` branch's history. Both `compare <red SHA>...<newer SHA>` and `compare <newer SHA>...<main tip>` must read `ahead` or `identical`, with the main tip read from `git/ref/heads/main`. Any other status, or a failed read, files as if no newer run had passed. A green run on a tag named `main` no longer suppresses the alert unless the tag points at a commit already on the branch.
- `scripts/run-plugin-tests.sh` prints `Advisory nonce: <16 hex>` before any suite block when advisory suites are on, and repeats the nonce in each advisory warning. The nonce is never exported to suites.
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
bump: patch
---

### Fixed

- **A merge can no longer lengthen its own quarantine.** The post-merge judge (`babysit_postmerge.py`, `check` and `--judge-run`) takes `merge.quarantine-days` as the smaller of its value at the red run's commit and at the last green full run's commit before it (the default, 7, when there is none), never above 30. A merged change that raises the value no longer keeps an out-of-set suite excused for longer.
- **One suite's output can no longer excuse another failing suite.** The judge credits a `failed ... but is advisory` warning only when it carries the nonce `scripts/run-plugin-tests.sh` prints before any suite block (`Advisory nonce: <16 hex>`). A warning printed inside a suite's block, or carrying any other nonce, excuses nothing, and that suite's failure demotes.
34 changes: 29 additions & 5 deletions .github/workflows/post-merge-demotion-alert.yml
Original file line number Diff line number Diff line change
Expand Up @@ -352,14 +352,30 @@ jobs:
# A dispatched red files nothing, and the report job skips it,
# once a newer full run on this repository's main has passed: main
# already recovered. newer_green prints that run as <id>\t<sha>,
# or nothing when there is none.
# or nothing when there is none. Only a run whose head descends
# from the red SHA and is on main's history counts (a ref named
# main, a tag included, can sit anywhere): compare red...newer and
# newer...<main's tip, read by heads/main> must each read ahead or
# identical, and any other status or a failed read prints nothing.
newer_green() {
gh api "repos/$GITHUB_REPOSITORY/actions/workflows/$RUN_WORKFLOW_ID/runs?branch=main&status=success&per_page=20" \
local found newer_id newer_sha ancestry main_tip on_main
found="$(gh api "repos/$GITHUB_REPOSITORY/actions/workflows/$RUN_WORKFLOW_ID/runs?branch=main&status=success&per_page=20" \
--jq '[.workflow_runs[] | select(.conclusion == "success" and .head_branch == "main"
and (.event | IN("schedule", "workflow_dispatch"))
and (.head_repository.full_name // "") == env.GITHUB_REPOSITORY
and (.id > (env.RUN_ID | tonumber) or .created_at > env.RUN_CREATED))]
| max_by(.created_at) // empty | [.id, .head_sha] | @tsv'
| max_by(.created_at) // empty | [.id, .head_sha] | @tsv')" || return 1
[[ -n "$found" ]] || return 0
IFS=$'\t' read -r newer_id newer_sha <<<"$found"
[[ "$newer_id" =~ ^[0-9]+$ && "$newer_sha" =~ ^[0-9a-f]{40}$ ]] || return 0
ancestry="$(gh api "repos/$GITHUB_REPOSITORY/compare/$RUN_SHA...$newer_sha" --jq '.status')" || return 0
[[ "$ancestry" == ahead || "$ancestry" == identical ]] || return 0
main_tip="$(gh api "repos/$GITHUB_REPOSITORY/git/ref/heads/main" --jq '.object.sha')" || return 0
[[ "$main_tip" =~ ^[0-9a-f]{40}$ ]] || return 0
on_main="$(gh api "repos/$GITHUB_REPOSITORY/compare/$newer_sha...$main_tip" --jq '.status')" || return 0
if [[ "$on_main" == ahead || "$on_main" == identical ]]; then
printf '%s\n' "$found"
fi
}
main_recovered() {
local newer_id newer_sha
Expand Down Expand Up @@ -438,13 +454,21 @@ jobs:
# Exit 0: every newly failing suite is outside the merges' affected
# set or quarantined, so each suite's quarantine issue is filed or
# commented and no record is. Exit 1: a suite demotes, which for a
# check red on the baseline too means its quarantine expired. Any
# other exit (the judge failed) files as before.
# check red on the baseline too means its quarantine expired. Exit 2
# to 4 (the judge failed) warns with its error and files as before,
# as does any other exit.
judged=0
judgment="$(python3 .base/plugins/source-control/skills/babysit-prs/scripts/babysit_postmerge.py \
--repo "$GITHUB_REPOSITORY" --judge-run "$RUN_ID" --attempt "$RUN_ATTEMPT" \
--checks-file "$now" --baseline-checks-file "$kept" --file-quarantine)" || judged=$?
printf '%s\n' "$judgment"
if ((judged >= 2 && judged <= 4)); then
error="$(jq -r '.error // empty' <<<"$judgment" 2>/dev/null)" || error=''
[[ -n "$error" ]] || error='no error in its output'
error="${error//'%'/%25}"
error="${error//$'\r'/%0D}"
echo "::warning::the suite judge exited $judged, so every newly failing check demotes: ${error//$'\n'/%0A}"
fi
if [[ "$judged" -eq 0 && -s "$now" ]]; then
echo "::notice::$RUN_URL failed only in suites outside the merges' affected set or quarantined: not a demotion"
echo 'excused=true' >>"$GITHUB_OUTPUT"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,9 @@
# picks nothing, has no set. A suite inside the set always
# demotes, quarantined or not. A suite outside it demotes nothing and is
# quarantined: with no open quarantine issue it gets one (`file_quarantines`);
# an open one older than `merge.quarantine-days` makes it demote again. The
# an open one older than `merge.quarantine-days` (the smaller of its value at
# that green SHA and at the red run's, `_Context._quarantine_days`) makes it
# demote again. The
# merge gate's own suites are never excused. post-merge-demotion-alert.yml applies the same rule through
# `--judge-run`.
SUITE_STEPS = {
Expand Down Expand Up @@ -848,8 +850,13 @@ def _full_history_clones() -> list[Path]:
_BASH_NO_RESULT = re.compile(
r"FAIL: (\S+\.test\.sh) \(no result recorded; the worker never reported\)"
)
# The runner prints a fresh nonce before any suite runs, in a variable no
# suite inherits, and repeats it in each advisory warning: a warning a suite's
# own output prints cannot carry it, so it excuses nothing.
_BASH_NONCE = re.compile(r"Advisory nonce: ([0-9a-f]{16})")
_BASH_ADVISORY = re.compile(
r"(?:::warning::|##\[warning\])(\S+) failed \(exit \d+\) but is advisory"
r" on this run \(nonce ([0-9a-f]{16})[;)]"
)
_PYTEST_CALL = re.compile(r"python -m pytest .* -- (\S+)")
_PYTEST_SUMMARY = re.compile(
Expand All @@ -869,18 +876,21 @@ def suite_failures(log: str, kind: str) -> frozenset[str] | None:
started: set[str] = set()
passed: set[str] = set()
advisory: set[str] = set()
nonce: str | None = None
for line in lines:
if line.startswith("DISCRIMINATING SKIP"):
return None
if m := _BASH_START.fullmatch(line):
if not started and nonce is None and (m := _BASH_NONCE.fullmatch(line)):
nonce = m[1]
elif m := _BASH_START.fullmatch(line):
started.add(m[1])
elif m := _BASH_PASS.fullmatch(line):
passed.add(m[1])
elif m := _BASH_FAIL.fullmatch(line) or _BASH_NO_RESULT.fullmatch(line):
failed.add(m[1])
if _BASH_NO_RESULT.fullmatch(line):
started.add(m[1])
elif m := _BASH_ADVISORY.match(line):
elif (m := _BASH_ADVISORY.match(line)) and m[2] == nonce:
advisory.add(m[1])
if started - passed - failed:
return None
Expand Down Expand Up @@ -1085,9 +1095,11 @@ class _Context:
default_factory=dict
)
# When quarantine issues are judged, and `merge.quarantine-days` (None:
# read at the red run's head the first time it is needed).
# read per red run, `_quarantine_days`).
now: datetime = field(default_factory=lambda: datetime.now(UTC))
quarantine_days: int | None = None
quarantine_days_cache: dict[int, int] = field(default_factory=dict)
green_cache: dict[int, Run | None] = field(default_factory=dict)
# `red-main.confirm-wait-minutes` plus FULL_RUN_ALLOWANCE (None: read at
# the branch tip the first time it is needed).
lane_rerun_window: timedelta | None = None
Expand Down Expand Up @@ -1201,7 +1213,7 @@ def expired(self, run: Run, attempt: int, checks: frozenset[str]) -> frozenset[s
if not named:
return frozenset()
issues = self._quarantine_issues()
days = self._quarantine_days(run.head_sha)
days = self._quarantine_days(run)
expired: set[str] = set()
for check, suites in named.items():
for suite in suites:
Expand Down Expand Up @@ -1234,7 +1246,7 @@ def demoting(
excused: list[Quarantine] = []
if judged:
issues = self._quarantine_issues()
days = self._quarantine_days(run.head_sha)
days = self._quarantine_days(run)
for check, suites in judged.items():
for suite in sorted(suites):
if (
Expand Down Expand Up @@ -1312,6 +1324,15 @@ def affected(self, run: Run) -> frozenset[str] | None:
full run before `run` and `run` itself (`affected_suites`), or None
when there is no such run or the set cannot be computed."""
if run.id not in self.affected_cache:
green = self._last_green(run)
self.affected_cache[run.id] = (
None if green is None else affected_suites(green.head_sha, run.head_sha)
)
return self.affected_cache[run.id]

def _last_green(self, run: Run) -> Run | None:
"""The branch's newest green full run before `run`, on another commit."""
if run.id not in self.green_cache:
created = quote(
f"<{run.created_at.astimezone(UTC).strftime('%Y-%m-%dT%H:%M:%SZ')}",
safe="",
Expand All @@ -1338,11 +1359,8 @@ def affected(self, run: Run) -> frozenset[str] | None:
and r.created_at < run.created_at
and r.head_sha != run.head_sha
]
green = self._newest_on_branch(greens)
self.affected_cache[run.id] = (
None if green is None else affected_suites(green.head_sha, run.head_sha)
)
return self.affected_cache[run.id]
self.green_cache[run.id] = self._newest_on_branch(greens)
return self.green_cache[run.id]

def on_branch(self, run: Run) -> bool:
"""Whether `run`'s head commit is on the branch as `refs/heads/`
Expand Down Expand Up @@ -1393,12 +1411,24 @@ def _newest_on_branch(self, runs: list[Run]) -> Run | None:
None,
)

def _quarantine_days(self, sha: str) -> int:
if self.quarantine_days is None:
self.quarantine_days = policy.read_config_at(
f"{self.owner}/{self.name}", sha
).quarantine_days
return self.quarantine_days
def _quarantine_days(self, run: Run) -> int:
"""`merge.quarantine-days` for `run`: the smaller of the value at its
head and at the last green full run's commit before it (the default
when there is none), so no merge in the window lengthens its own
quarantine, and never above `MAX_QUARANTINE_DAYS`."""
if self.quarantine_days is not None:
return self.quarantine_days
if run.id not in self.quarantine_days_cache:
repo = f"{self.owner}/{self.name}"
green = self._last_green(run)
self.quarantine_days_cache[run.id] = min(
policy.read_config_at(repo, run.head_sha).quarantine_days,
policy.QUARANTINE_DAYS
if green is None
else policy.read_config_at(repo, green.head_sha).quarantine_days,
policy.MAX_QUARANTINE_DAYS,
)
return self.quarantine_days_cache[run.id]

def lane_rerun_lookback(self) -> timedelta:
if self.lane_rerun_window is None:
Expand Down Expand Up @@ -3817,7 +3847,7 @@ def _judge_run(args: argparse.Namespace) -> int:
quarantines,
agent_identity=identity,
branch=ctx.branch,
days=ctx._quarantine_days(run.head_sha),
days=ctx._quarantine_days(run),
report=report["quarantine"],
)
except (PostMergeReadError, PostMergeWriteError) as exc:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,27 @@
SIGHTING = f"{RUN_URL}/11/attempts/2"


def bash_log(*results: tuple[str, bool], tail: str = "") -> str:
"""A test-bash leg's log: each suite's block, then PASS or FAIL."""
NONCE = "0123456789abcdef"


def advisory(suite: str, nonce: str = NONCE) -> str:
"""The runner's warning for a failing advisory suite."""
return (
f"::warning::{suite} failed (exit 1) but is advisory on this run "
f"(nonce {nonce}; PLUGIN_TEST_ADVISORY=1, scripts/run-plugin-tests-advisory.txt)"
)


def bash_log(
*results: tuple[str, bool], tail: str = "", inside: dict[str, str] | None = None
) -> str:
"""A test-bash leg's log: the runner's advisory nonce, then each suite's
block (with `inside[suite]` among its own output), then PASS or FAIL."""
lines = ["##[group]Run jq -r --arg leg ...", "##[endgroup]"]
lines += [f"Advisory nonce: {NONCE}"]
for suite, ok in results:
lines += [f"=== {suite} ===", "FAIL: a case inside the suite"]
lines += [(inside or {}).get(suite, "")]
lines += [f"{'PASS' if ok else 'FAIL'}: {suite}"]
lines += [tail, "One or more plugin tests failed."]
return "\n".join(STAMP + line for line in lines)
Expand Down Expand Up @@ -314,6 +330,38 @@ def test_expiry_restores_demotion(self) -> None:
self.assertEqual([f.signal for f in verdict.failures], ["dispatch"])
self.assertEqual(verdict.quarantines, ())

def quarantine_days_at(self, days: dict[str, int]) -> None:
"""`merge.quarantine-days` by the SHA it is read at (default 7)."""
self.read_config.side_effect = lambda repo, sha, *a, **k: mock.Mock(
quarantine_days=days.get(sha, policy.QUARANTINE_DAYS),
confirm_wait_minutes=policy.CONFIRM_WAIT_MINUTES,
)

def test_raising_quarantine_days_at_the_red_sha_does_not_lengthen_it(
self,
) -> None:
# 7 days at the last green run's commit, 30 at the red one: the issue
# filed 8 days ago has expired, so the suite demotes.
self.quarantine_days_at({OTHER_SHA: 7, LATER_SHA: 30})
self.quarantine_issue(FLAKY, "2026-10-04T10:00:00Z")
self.red_dispatch(bash_log((FLAKY, False)))
verdict = self.check()
self.assertEqual([f.signal for f in verdict.failures], ["dispatch"])

def test_a_lowered_quarantine_days_at_the_red_sha_shortens_it(self) -> None:
# 30 at the base, 3 at the red commit: the issue filed 4 days ago expired.
self.quarantine_days_at({OTHER_SHA: 30, LATER_SHA: 3})
self.quarantine_issue(FLAKY, "2026-10-08T10:00:00Z")
self.red_dispatch(bash_log((FLAKY, False)))
self.assertEqual([f.signal for f in self.check().failures], ["dispatch"])

def test_quarantine_days_agreeing_at_both_shas_still_excuses(self) -> None:
# 10 at both: the issue filed 8 days ago is still open.
self.quarantine_days_at({OTHER_SHA: 10, LATER_SHA: 10})
self.quarantine_issue(FLAKY, "2026-10-04T10:00:00Z")
self.red_dispatch(bash_log((FLAKY, False)))
self.assertEqual(self.check().failures, ())

def red_baseline(self) -> None:
"""Dispatch run 10, before the merge, red on the same leg."""
self.gh.add_runs(
Expand Down Expand Up @@ -769,10 +817,32 @@ def test_bash_names_the_failing_suites_and_drops_advisory_ones(self) -> None:
(FLAKY, False),
(TOUCHED, False),
(GATE, True),
tail=f"::warning::{TOUCHED} failed (exit 1) but is advisory on this run",
tail=advisory(TOUCHED),
)
self.assertEqual(pm.suite_failures(log, "bash"), frozenset({FLAKY}))

def test_an_advisory_line_inside_another_suites_block_excuses_nothing(
self,
) -> None:
# FLAKY's own output prints TOUCHED's advisory warning, with the
# nonce guessed wrong or copied from an older run.
for forged in (advisory(TOUCHED, "f" * 16), advisory(TOUCHED, "")):
with self.subTest(forged):
log = bash_log((FLAKY, False), (TOUCHED, False), inside={FLAKY: forged})
self.assertEqual(
pm.suite_failures(log, "bash"), frozenset({FLAKY, TOUCHED})
)

def test_a_nonce_line_inside_a_block_is_not_the_runners(self) -> None:
# A suite prints its own nonce line and a warning carrying it; only
# the runner's line, before any block, sets the nonce.
forged = f"Advisory nonce: {'e' * 16}"
log = bash_log(
(FLAKY, False), (TOUCHED, False), inside={FLAKY: forged}
).replace(f"Advisory nonce: {NONCE}", "Suites: 2")
log += "\n" + STAMP + advisory(TOUCHED, "e" * 16)
self.assertEqual(pm.suite_failures(log, "bash"), frozenset({FLAKY, TOUCHED}))

def test_a_real_leg_log_names_only_runner_suites(self) -> None:
# Job 119563204870: the ui suite's own output prints `FAIL: <file>`
# lines, and the runner's stderr `FAIL: <suite>` lands inside them.
Expand Down
Loading
Loading