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
ci(bench): fail the strict threshold step when the checker exits 1
Actions dot-sources shell: pwsh, so the call operator only sets
$LASTEXITCODE. Re-exit with that code so a -Strict failure fails the job.

Co-authored-by: Andrew Brown <lazyxeon@users.noreply.github.com>
  • Loading branch information
cursoragent and lazyxeon committed Nov 5, 2026
commit d268a4b8e38471cb9c715e902390d0ff2f1e97d8
3 changes: 3 additions & 0 deletions .github/workflows/benchmark.yml
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,9 @@ jobs:
-ThresholdsJsonPath ".github/benchmark_thresholds.json" `
-Strict `
-ShowDetails
# Actions dot-sources shell: pwsh. exit in the called script only
# sets $LASTEXITCODE, so a -Strict failure would leave the job green.
exit $LASTEXITCODE
Comment on lines +360 to +362

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The strict step's process exit on a hosted runner is already the checker's $LASTEXITCODE. actions/runner ScriptHandlerHelpers.FixUpScriptContents (tag v2.328.0 and main) rewrites every shell: pwsh script before pwsh -command ". '{0}'":

$ErrorActionPreference = 'stop'
# step body
if ((Test-Path -LiteralPath variable:\LASTEXITCODE)) { exit $LASTEXITCODE }

I ran the pre-change body inside that wrapper against .github/benchmark_thresholds.json (astraweave-core::ecs_benchmarks/world_creation, baseline 25.8, max 38.7). pwsh 7.4.6 and 7.6.6 both exited 1 for value 39.7, for a missing results file, and for a non-numeric value, and exited 0 for the baseline. After the checker, Test-Path variable:\LASTEXITCODE is true and the value is 1, so the appended if runs. The wrapper-less dot-source exits 0 with $LASTEXITCODE=1. That is the #693 repro, and it leaves out this rewrite.

exit $LASTEXITCODE here returns those same codes, and the append never runs. The comment says a -Strict failure would leave the job green. On the runner that executes this step, the pre-change body already exits 1.


- name: Report aggregate package status
if: always()
Expand Down
207 changes: 206 additions & 1 deletion scripts/ci/test_workflow_policy.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,19 @@
#!/usr/bin/env python3
"""Static checks for the CI tiering rules. Does not call GitHub."""
"""CI tiering checks. Does not call GitHub.

The benchmark.yml Strict step is executed under Actions' pwsh dot-source
shape (`pwsh -command ". '{0}'"`). A swallowed $LASTEXITCODE fails that test.
"""

from __future__ import annotations

import inspect
import json
import re
import shutil
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path

Expand Down Expand Up @@ -321,6 +329,179 @@ def assert_mutation_summary_checks_out_before_scoring(text: str) -> None:
raise AssertionError("checkout must precede mutation_ai_outcomes.py in mutants-summary")


STRICT_THRESHOLD_STEP = "Strict threshold validation (main branch only)"
BENCHMARK_JSON_ARG = '"benchmark_results/benchmarks.json"'
THRESHOLDS_JSON_ARG = '".github/benchmark_thresholds.json"'


def _step_shell(step_block: str) -> str | None:
for line in step_block.splitlines():
stripped = line.strip()
if stripped.startswith("shell:"):
return stripped.split(":", 1)[1].strip()
if stripped.startswith("run:"):
return None
return None


def _yaml_literal_run(step_block: str) -> str:
raw = _run_script(step_block)
if not raw.lstrip().startswith("|"):
raise AssertionError("Strict threshold step run: must be a literal block")
lines = raw.splitlines()[1:]
while lines and not lines[-1].strip():
lines.pop()
if not lines:
raise AssertionError("Strict threshold step run: block is empty")
indents = [len(line) - len(line.lstrip(" ")) for line in lines if line.strip()]
cut = min(indents)
dedented: list[str] = []
for line in lines:
if not line.strip():
dedented.append("")
continue
if not line.startswith(" " * cut):
raise AssertionError("Strict threshold step run: inconsistent indent")
dedented.append(line[cut:])
return "\n".join(dedented) + "\n"


def strict_threshold_step_body(text: str) -> str:
block = job_step_block(text, STRICT_THRESHOLD_STEP)
if "continue-on-error:" in block:
raise AssertionError("Strict threshold step must not set continue-on-error")
if _step_shell(block) != "pwsh":
raise AssertionError(
"Strict threshold step must use shell: pwsh; Actions dot-sources that shell"
)
if "github.ref == 'refs/heads/main'" not in block:
Comment on lines +371 to +377

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

These guards do not keep the Strict step on main, and they do not see a job-level continue-on-error.

On this head, strict_threshold_step_body accepts both of these edits:

  • if: steps.merge.outputs.healthy == 'true' && github.ref == 'refs/heads/main' && false
  • that if replaced by if: steps.merge.outputs.healthy == 'true' plus a comment # github.ref == 'refs/heads/main'

continue-on-error: true on the aggregate job is also accepted. job_step_block stops at the next step, so the job key is outside block.

assert_strict_threshold_step_propagates_checker_exit then dot-sources the run body and never evaluates if. A Strict step that does not run on main still passes. This is the #696 gap.

raise AssertionError("Strict threshold step must stay main-branch only")
body = _yaml_literal_run(block)
statements = [
line.strip()
for line in body.splitlines()
if line.strip() and not line.strip().startswith("#")
]
if not any(line.split()[:1] == ["-Strict"] for line in statements):
raise AssertionError("Strict threshold step must pass -Strict")
if THRESHOLDS_JSON_ARG not in body:
raise AssertionError(
"Strict threshold step must use .github/benchmark_thresholds.json"
)
if BENCHMARK_JSON_ARG not in body:
raise AssertionError(
"Strict threshold step must read benchmark_results/benchmarks.json"
)
return body


def _ps_single_quote(value: str) -> str:
return "'" + value.replace("'", "''") + "'"


def _threshold_pair(thresholds: Path) -> tuple[list[dict[str, object]], list[dict[str, object]]]:
data = json.loads(thresholds.read_text(encoding="utf-8"))
benchmarks = data.get("benchmarks")
if not isinstance(benchmarks, dict) or not benchmarks:
raise AssertionError(f"{thresholds} has no benchmarks")
for name, spec in benchmarks.items():
if not isinstance(spec, dict):
continue
baseline = spec.get("baseline")
max_allowed = spec.get("max_allowed")
if not isinstance(baseline, (int, float)) or not isinstance(max_allowed, (int, float)):
continue
if baseline <= 0 or max_allowed < baseline:
continue
unit = spec.get("unit", "ns")
over = [{"name": name, "value": float(max_allowed) + 1.0, "unit": unit}]
under = [{"name": name, "value": float(baseline), "unit": unit}]
return over, under
raise AssertionError(f"{thresholds} has no benchmark with 0 < baseline <= max_allowed")


def _require_pwsh() -> str:
pwsh = shutil.which("pwsh")
if pwsh is None:
raise AssertionError("pwsh is required to prove the Strict step process exit")
return pwsh


def _run_pwsh(args: list[str], *, cwd: Path) -> subprocess.CompletedProcess[str]:
return subprocess.run(
args,
cwd=cwd,
capture_output=True,
text=True,
timeout=60,
check=False,
)


def _checker_file_exit(benchmark_json: Path, thresholds: Path, root: Path) -> int:
proc = _run_pwsh(
[
_require_pwsh(),
"-NoLogo",
"-File",
str(root / "scripts" / "check_benchmark_thresholds.ps1"),
"-BenchmarkJsonPath",
str(benchmark_json),
"-ThresholdsJsonPath",
str(thresholds),
"-ShowDetails",
"-Strict",
],
cwd=root,
)
return proc.returncode


def _dotsource_exit(body: str, benchmark_json: Path, root: Path) -> tuple[int, str]:
"""Run a step body the way Actions runs shell: pwsh (`pwsh -command ". '{0}'"`)."""
rendered = body.replace(BENCHMARK_JSON_ARG, _ps_single_quote(str(benchmark_json)), 1)
with tempfile.TemporaryDirectory(prefix="gha-strict-") as tmp:
step = Path(tmp) / "gha-strict-step.ps1"
step.write_text(rendered, encoding="utf-8")
command = ". '{0}'".format(str(step).replace("'", "''"))
proc = _run_pwsh(
[_require_pwsh(), "-NoLogo", "-Command", command],
cwd=root,
)
output = (proc.stdout or "") + (proc.stderr or "")
return proc.returncode, output
Comment on lines +460 to +472

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

_dotsource_exit launches pwsh -NoLogo -Command ". '{0}'" on the step body alone. The runner also prepends $ErrorActionPreference = 'stop' and appends if ((Test-Path -LiteralPath variable:\LASTEXITCODE)) { exit $LASTEXITCODE }. test_strict_threshold_dotsource_without_reexit_stays_zero deletes exit $LASTEXITCODE and requires process exit 0. With the runner wrapper, that deletion still exits 1 (same fixtures, pwsh 7.4.6 and 7.6.6).

The suite is 38 tests, exit 0, on both versions. It locks the wrapper-less shape, which is the shape shell: pwsh does not execute. A hosted-runner log of the old step with process exit 0 would overturn this. I do not have one.



def assert_strict_threshold_step_propagates_checker_exit(
text: str, *, root: Path = ROOT
) -> None:
body = strict_threshold_step_body(text)
thresholds = root / ".github" / "benchmark_thresholds.json"
over, under = _threshold_pair(thresholds)
with tempfile.TemporaryDirectory(prefix="bench-threshold-") as tmp:
tmp_path = Path(tmp)
over_path = tmp_path / "over.json"
under_path = tmp_path / "under.json"
over_path.write_text(json.dumps(over), encoding="utf-8")
under_path.write_text(json.dumps(under), encoding="utf-8")
if _checker_file_exit(over_path, thresholds, root) == 0:
raise AssertionError(
"check_benchmark_thresholds.ps1 -Strict exits 0 for an over-limit result"
)
over_code, over_out = _dotsource_exit(body, over_path, root)
if over_code == 0:
raise AssertionError(
"Strict threshold step process exit is 0 when the checker fails\n"
+ over_out[-1500:]
)
under_code, under_out = _dotsource_exit(body, under_path, root)
if under_code != 0:
raise AssertionError(
"Strict threshold step process exit is "
f"{under_code} when results are within thresholds\n" + under_out[-1500:]
)


def assert_mutation_ai_scoring_uses_strict_eval(text: str) -> None:
ai = mutation_ai_job(text)
report = job_step_block(ai, "Generate mutation report")
Expand Down Expand Up @@ -844,6 +1025,30 @@ def test_mutation_ai_outcomes_verify_shard_rejects_unfinished(self) -> None:
)
self.assertEqual(exit_code, 1)

def test_strict_threshold_dotsource_fails_when_checker_fails(self) -> None:
text = (WORKFLOWS / "benchmark.yml").read_text(encoding="utf-8")
assert_strict_threshold_step_propagates_checker_exit(text)

def test_strict_threshold_dotsource_without_reexit_stays_zero(self) -> None:
text = (WORKFLOWS / "benchmark.yml").read_text(encoding="utf-8")
broken = "".join(
line
for line in text.splitlines(keepends=True)
if line.strip() != "exit $LASTEXITCODE"
)
self.assertNotEqual(broken, text)
with self.assertRaises(AssertionError) as caught:
assert_strict_threshold_step_propagates_checker_exit(broken)
self.assertIn("process exit is 0", str(caught.exception))

def test_strict_threshold_hardcoded_exit_fails_a_clean_result(self) -> None:
text = (WORKFLOWS / "benchmark.yml").read_text(encoding="utf-8")
broken = text.replace("exit $LASTEXITCODE", "exit 1", 1)
self.assertNotEqual(broken, text)
with self.assertRaises(AssertionError) as caught:
assert_strict_threshold_step_propagates_checker_exit(broken)
self.assertIn("within thresholds", str(caught.exception))

def test_mutation_ai_verify_errors_are_required(self) -> None:
source = (ROOT / "scripts" / "ci" / "mutation_ai_outcomes.py").read_text(encoding="utf-8")
self.assertIn(VERIFY_BASELINE_ERROR, source)
Expand Down
Loading