Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(ci): enforce release scenario evidence results (#2948)
Call White3737f7b907a4
diff --git a/.github/workflows/model-hub-e2e.yml b/.github/workflows/model-hub-e2e.ymlindex 2cec25d3e..f747e24f7 100644--- a/.github/workflows/model-hub-e2e.yml+++ b/.github/workflows/model-hub-e2e.yml@@ -81,11 +81,25 @@ jobs:# Every scenario is hermetic, so it runs where only loopback answers: an# engine or CLI that ignores its loopback upstream fails at once instead# of reaching a real provider. The downloads above stay outside.- - name: Run the Model Hub E2E+ - name: Prepare Model Hub E2E junit directory+ run: mkdir -p "$RUNNER_TEMP/model-hub-e2e-junit"++ # Every release E2E case selected below must be present and passing in this+ # run's own report; collection or a green process is not enough.+ - name: Run the Model Hub E2E and release evidence gaterun: |bash scripts/ci_loopback_only.sh python -m pytest -m e2e_model_hub tests/e2e -p no:cacheprovider -ra \- --basetemp="$RUNNER_TEMP/e2e" 2>&1 | tee model-hub-e2e.log- exit "${PIPESTATUS[0]}"+ --basetemp="$RUNNER_TEMP/e2e" \+ --junitxml="$RUNNER_TEMP/model-hub-e2e-junit/model-hub-e2e.xml" 2>&1 | tee model-hub-e2e.log || pytest_status=${PIPESTATUS[0]}+ pytest_status=${pytest_status:-0}+ python scripts/ci_scenario_evidence.py --release \+ "$RUNNER_TEMP/model-hub-e2e-junit" \+ --workflow .github/workflows/model-hub-e2e.yml \+ --pytest-root . \+ --pytest-command-index 0 || evidence_status=$?+ evidence_status=${evidence_status:-0}+ if [ "$pytest_status" -ne 0 ]; then exit "$pytest_status"; fi+ exit "$evidence_status"- name: Upload the run logif: always()diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.ymlindex 3fe95867d..57c952015 100644--- a/.github/workflows/publish.yml+++ b/.github/workflows/publish.yml@@ -181,6 +181,10 @@ jobs:scripts/show_runtime_manifest_asset.pyscripts/build_retired_companion.pyscripts/release_package_version.py+ scripts/ci_scenario_evidence.py+ scripts/pytest_collection.py+ .github/workflows/publish.yml+ tests/scenarios/**/catalog.yamltests/test_distribution_artifacts.pytests/__init__.pytests/e2e/test_retired_updater_bridge.py@@ -360,7 +364,18 @@ jobs:PY)"if [ "$UPGRADE_DIRECTION" = forward ]; then- (cd release-automation && python -m pytest tests/e2e/test_retired_updater_bridge.py -v)+ mkdir -p "$RUNNER_TEMP/retired-updater-junit"+ pytest_status=0+ (cd release-automation && python -m pytest tests/e2e/test_retired_updater_bridge.py -v \+ --junitxml="$RUNNER_TEMP/retired-updater-junit/retired-updater-bridge.xml") || pytest_status=$?+ evidence_status=0+ (cd release-automation && python scripts/ci_scenario_evidence.py --release \+ "$RUNNER_TEMP/retired-updater-junit" \+ --workflow .github/workflows/publish.yml \+ --pytest-root . \+ --pytest-command-index 1) || evidence_status=$?+ if [ "$pytest_status" -ne 0 ]; then exit "$pytest_status"; fi+ exit "$evidence_status"elseecho "No forward Memory retirement upgrade from v3.1.0 to $RELEASE_TAG"fidiff --git a/scripts/ci_scenario_evidence.py b/scripts/ci_scenario_evidence.pyindex c209c39b7..cd57aece7 100644--- a/scripts/ci_scenario_evidence.py+++ b/scripts/ci_scenario_evidence.py@@ -1,33 +1,26 @@-"""Gate: every case a ``covered`` scenario row cites as evidence ran and passed in CI, or a release runs it.--The citation check (``tests/scenarios/test_catalog_citations.py``) proves each-cited case is one pytest collects, but not that CI runs it: a ``skipif`` whose-condition always holds in CI, an imperative ``pytest.skip()``,-``xfail(run=False)``, a parameter set marked skip, or a deselecting hook each-leave a ``covered`` row with nothing that runs. MESSAGE-DELIVERY-034 read-``covered`` while its only case needed an explicitly selected Codex binary.-This reads what CI ran: every pytest run in ``lint.yml`` writes a junit report-(``AVIBE_CI_JUNIT_DIR``, ``tests/conftest.py``), and each job uploads its own.--An evidence case passes when it passed in at least one report, so a case-skipped on one platform passes when it ran on another. Otherwise it is:--- **release-gated** when a pytest command of a release workflow selects it, as- pytest's own collection of that command's arguments decides. A release needs- those workflows green at its SHA (``docs/release.md``), and the Model Hub E2E- runs nowhere else;-- **not run** when a ``lint.yml`` job that selects it left no report on this- run, because its path or event filter skipped it. Nothing is known about the- case then, so it does not fail;-- **failing** otherwise: skipped everywhere it ran, with the reasons pytest- recorded, or collected by no job that ran.--Usage: ``python scripts/ci_scenario_evidence.py <junit-dir>``, where each+"""Gate covered scenario evidence in PR CI and in the release workflows.++The PR citation check (``tests/scenarios/test_catalog_citations.py``) proves+that each cited case is collected, while this gate reads the JUnit records from+pytest itself. A normal CI run may classify a case as ``release-gated`` because+its release workflow selects it; release mode is stricter and requires every+selected covered ``test`` case to have a passing JUnit record from that release+run.++PR usage: ``python scripts/ci_scenario_evidence.py <junit-dir>``, where eachsubdirectory is one job's ``junit-<job>-<index>`` artifact.++Release usage: ``python scripts/ci_scenario_evidence.py --release <junit-dir>+--workflow <workflow> --pytest-root <root> --pytest-command-index <index>``.+The workflow command is collected from ``<root>`` and its one JUnit report is+required to contain a passing result for every covered case that command+selects. The explicit root is important for ``publish.yml``: its retired+updater test runs from the separate ``release-automation`` checkout."""from __future__ import annotations+import argparseimport reimport shleximport sys@@ -55,6 +48,10 @@ _VALUED = {"-m", "-k", "-p", "-c", "-o", "--ignore", "--deselect", "--rootdir"}_SEPARATORS = re.compile(r"\s*(?:&&|\|\||;|\|)\s*")+class ReleaseEvidenceError(RuntimeError):+ """A release evidence contract is missing or records a non-passing case."""++@dataclassclass Evidence:"""One case a ``covered`` row cites, the rows citing it, and what CI recorded for it."""@@ -87,6 +84,22 @@ def covered_evidence(scenario_root: Path = SCENARIO_ROOT) -> dict[str, Evidence]return evidence+def covered_test_evidence(scenario_root: Path = SCENARIO_ROOT) -> dict[str, Evidence]:+ """The covered rows' primary ``test`` evidence, excluding #2775 partial evidence."""++ evidence: dict[str, Evidence] = {}+ for catalog in sorted(scenario_root.glob("*/catalog.yaml")):+ for row in yaml.safe_load(catalog.read_text(encoding="utf-8")).get("scenarios") or []:+ if row.get("status") != "covered":+ continue+ cited = row.get("test")+ cited = list(cited) if isinstance(cited, list) else [cited]+ for citation in cited:+ if isinstance(citation, str) and citation.partition("::")[0].endswith(".py") and "::" in citation:+ evidence.setdefault(citation, Evidence(citation, [])).rows.append(row["id"])+ return evidence++def names_case(citation: str, nodeid: str) -> bool:"""Whether ``nodeid`` is a run of the case ``citation`` names, by the citation check's rule."""@@ -153,6 +166,54 @@ def read_reports(junit_dir: Path, repo_root: Path = REPO_ROOT) -> Reports:return reports+def read_release_report(junit_dir: Path, repo_root: Path = REPO_ROOT) -> dict[str, tuple[str, str]]:+ """Read exactly one non-empty release JUnit report, failing closed on bad input."""++ if not junit_dir.is_dir():+ raise ReleaseEvidenceError(f"release JUnit directory does not exist: {junit_dir}")+ reports = sorted(path for path in junit_dir.rglob("*.xml") if path.is_file())+ if not reports:+ raise ReleaseEvidenceError(f"release JUnit directory is empty: {junit_dir}")+ if len(reports) != 1:+ names = ", ".join(str(path.relative_to(junit_dir)) for path in reports)+ raise ReleaseEvidenceError(+ f"release JUnit directory must contain exactly one report, found {len(reports)}: {names}"+ )++ report = reports[0]+ try:+ root = ElementTree.parse(report).getroot()+ except (ElementTree.ParseError, OSError) as exc:+ raise ReleaseEvidenceError(f"could not parse release JUnit report {report}: {exc}") from exc+ cases = list(root.iter("testcase"))+ if not cases:+ raise ReleaseEvidenceError(f"release JUnit report contains no testcases: {report}")++ outcomes: dict[str, tuple[str, str]] = {}+ for case in cases:+ nodeid = _nodeid(case.get("classname", ""), case.get("name", ""), repo_root)+ if nodeid is None:+ continue+ failure = case.find("failure")+ error = case.find("error")+ skipped = case.find("skipped")+ if failure is not None or error is not None:+ outcome = ("failed", (failure if failure is not None else error).get("message", ""))+ elif skipped is not None:+ outcome = ("skipped", skipped.get("message", "") or skipped.get("type", ""))+ else:+ outcome = ("passed", "")+ if nodeid in outcomes and outcomes[nodeid] != outcome:+ raise ReleaseEvidenceError(f"release JUnit report records {nodeid} more than once")+ outcomes[nodeid] = outcome++ if not outcomes:+ raise ReleaseEvidenceError(+ f"release JUnit report contains no testcases from checkout {repo_root}: {report}"+ )+ return outcomes++def matrix_size(job: dict) -> int:"""How many runs a job's matrix makes: the product of its value lists, or its ``include`` entries alone."""@@ -218,6 +279,73 @@ def _selecting_args(tokens: list[str]) -> tuple[str, ...] | None:return tuple(selecting)+def release_pytest_commands(workflow: Path) -> list[tuple[str, ...]]:+ """The parsed pytest commands in workflow order for a release contract."""++ return [args for commands in pytest_commands(workflow).values() for args in commands]+++def check_release_evidence(+ junit_dir: Path,+ workflow: Path,+ pytest_root: Path,+ pytest_command_index: int = 0,+ scenario_root: Path = SCENARIO_ROOT,+) -> dict[str, list[str]]:+ """Require every covered case selected by one release command to pass in its JUnit report."""++ if not workflow.is_file():+ raise ReleaseEvidenceError(f"release workflow does not exist: {workflow}")+ if not pytest_root.is_dir():+ raise ReleaseEvidenceError(f"release pytest checkout does not exist: {pytest_root}")+ commands = release_pytest_commands(workflow)+ if not commands:+ raise ReleaseEvidenceError(f"could not parse a pytest command from release workflow: {workflow}")+ if not 0 <= pytest_command_index < len(commands):+ raise ReleaseEvidenceError(+ f"release workflow has {len(commands)} parsed pytest command(s), "+ f"but --pytest-command-index is {pytest_command_index}: {workflow}"+ )++ args = commands[pytest_command_index]+ from scripts import pytest_collection++ try:+ collected = pytest_collection.collect(list(args), pytest_root)+ except Exception as exc:+ raise ReleaseEvidenceError(+ f"could not collect release pytest command from {pytest_root}: {' '.join(args)}: {exc}"+ ) from exc+ selected: dict[str, list[str]] = {}+ for citation in covered_test_evidence(scenario_root):+ nodeids = [entry["nodeid"] for entry in collected if names_case(citation, entry["nodeid"])]+ if nodeids:+ selected[citation] = nodeids+ if not selected:+ raise ReleaseEvidenceError(+ "parsed release pytest command selects no covered scenario test evidence: "+ + " ".join(args)+ )++ outcomes = read_release_report(junit_dir, pytest_root)+ problems: list[str] = []+ for citation, nodeids in selected.items():+ missing = [nodeid for nodeid in nodeids if nodeid not in outcomes]+ if missing:+ problems.append(f"{citation} is missing from the release JUnit report: {', '.join(missing)}")+ continue+ failed = [+ f"{nodeid}={outcomes[nodeid][0]}{': ' + outcomes[nodeid][1] if outcomes[nodeid][1] else ''}"+ for nodeid in nodeids+ if outcomes[nodeid][0] != "passed"+ ]+ if failed:+ problems.append(f"{citation} did not pass in the release run ({'; '.join(failed)})")+ if problems:+ raise ReleaseEvidenceError("; ".join(problems))+ return selected++def judge(evidence: dict[str, Evidence],reports: Reports,@@ -282,11 +410,46 @@ def judge(return problems, accounted+def _parse_args(argv: list[str]) -> argparse.Namespace:+ parser = argparse.ArgumentParser()+ parser.add_argument("junit_dir", help="JUnit directory to inspect")+ parser.add_argument("--release", action="store_true", help="enforce the release-run evidence contract")+ parser.add_argument("--workflow", type=Path, help="release workflow containing the pytest command")+ parser.add_argument("--pytest-root", type=Path, default=Path.cwd(), help="checkout root used by that pytest command")+ parser.add_argument("--pytest-command-index", type=int, default=0, help="parsed pytest command to verify")+ return parser.parse_args(argv)+++def _path_from_cwd(path: Path) -> Path:+ return path if path.is_absolute() else (Path.cwd() / path).resolve()++def main(argv: list[str]) -> int:+ args = _parse_args(argv)+ if args.release:+ if args.workflow is None:+ print("::error::release mode requires --workflow")+ return 1+ try:+ selected = check_release_evidence(+ _path_from_cwd(Path(args.junit_dir)),+ _path_from_cwd(args.workflow),+ _path_from_cwd(args.pytest_root),+ args.pytest_command_index,+ )+ except ReleaseEvidenceError as exc:+ print(f"::error::{exc}")+ return 1+ print(+ f"Release evidence passed for {len(selected)} covered test case(s) "+ f"from {args.workflow} using checkout {_path_from_cwd(args.pytest_root)}."+ )+ return 0+from scripts import pytest_collection- (junit_dir,) = argv- reports = read_reports(Path(junit_dir))+ junit_dir = Path(args.junit_dir)+ reports = read_reports(junit_dir)lint_commands = pytest_commands(WORKFLOWS / LINT_WORKFLOW)lint_runs = {job_id: matrix_size(job) for job_id, job in workflow_jobs(WORKFLOWS / LINT_WORKFLOW).items()}release_commands = [args for name in RELEASE_WORKFLOWS for commands in pytest_commands(WORKFLOWS / name).values() for args in commands]diff --git a/scripts/pytest_collection.py b/scripts/pytest_collection.pyindex 84dc4ac2c..684b7589e 100644--- a/scripts/pytest_collection.py+++ b/scripts/pytest_collection.py@@ -73,7 +73,7 @@ def collect(args: list[str], cwd: Path = REPO_ROOT) -> list[dict]:# or a CI junit directory this run has nothing to report to.env={**{name: value for name, value in os.environ.items() if name not in ("PYTEST_ADDOPTS", "AVIBE_CI_JUNIT_DIR")},- "PYTHONPATH": os.pathsep.join(filter(None, [str(REPO_ROOT), os.environ.get("PYTHONPATH")])),+ "PYTHONPATH": os.pathsep.join(filter(None, [str(cwd), str(REPO_ROOT), os.environ.get("PYTHONPATH")])),},capture_output=True,text=True,diff --git a/tests/test_ci_scenario_evidence.py b/tests/test_ci_scenario_evidence.pyindex 81152e9a8..5605136f8 100644--- a/tests/test_ci_scenario_evidence.py+++ b/tests/test_ci_scenario_evidence.py@@ -13,11 +13,15 @@ from scripts.ci_scenario_evidence import (UNIT_SHARD_JOB,WORKFLOWS,Evidence,+ ReleaseEvidenceError,Reports,+ check_release_evidence,covered_evidence,+ covered_test_evidence,judge,pytest_commands,read_reports,+ release_pytest_commands,)CASE = "tests/test_x.py::test_case"@@ -34,6 +38,71 @@ def _reports(**jobs: dict[str, tuple[str, str]]) -> Reports:return reports+def _release_fixture(tmp_path: Path) -> tuple[Path, Path, Path, Path]:+ root = tmp_path / "checkout"+ test = root / "tests" / "test_x.py"+ test.parent.mkdir(parents=True)+ test.write_text("def test_case():\n pass\n", encoding="utf-8")+ scenarios = root / "tests" / "scenarios" / "capability"+ scenarios.mkdir(parents=True)+ scenarios.joinpath("catalog.yaml").write_text(+ "scenarios:\n - id: ROW-1\n status: covered\n test: tests/test_x.py::test_case\n",+ encoding="utf-8",+ )+ workflow = tmp_path / "workflow.yml"+ workflow.write_text(+ "jobs:\n release:\n steps:\n - run: python -m pytest tests/test_x.py --junitxml=report.xml\n",+ encoding="utf-8",+ )+ junit = tmp_path / "junit"+ junit.mkdir()+ return root, scenarios.parent, workflow, junit+++def _write_release_report(junit: Path, body: str) -> None:+ junit.joinpath("release.xml").write_text(+ f"<testsuites><testsuite>{body}</testsuite></testsuites>", encoding="utf-8"+ )+++ "result",+ [+ "",+ '<skipped message="conditional skip"/>',+ '<failure message="assertion failed"/>',+ '<error message="fixture error"/>',+ '<skipped type="pytest.xfail" message="known gap"/>',+ ],+ ids=["pass", "skip", "failure", "error", "xfail"],+)+def test_release_evidence_requires_a_passing_junit_case(tmp_path: Path, result: str) -> None:+ root, scenarios, workflow, junit = _release_fixture(tmp_path)+ _write_release_report(junit, f'<testcase classname="tests.test_x" name="test_case">{result}</testcase>')++ if result:+ with pytest.raises(ReleaseEvidenceError, match="did not pass in the release run"):+ check_release_evidence(junit, workflow, root, scenario_root=scenarios)+ else:+ assert check_release_evidence(junit, workflow, root, scenario_root=scenarios) == {+ CASE: [CASE]+ }++[email protected]("report_state", ["missing", "empty", "malformed"])+def test_release_evidence_fails_closed_for_bad_reports(tmp_path: Path, report_state: str) -> None:+ root, scenarios, workflow, junit = _release_fixture(tmp_path)+ if report_state == "missing":+ junit = tmp_path / "missing-junit"+ elif report_state == "empty":+ junit.joinpath("release.xml").write_text("<testsuites/>", encoding="utf-8")+ elif report_state == "malformed":+ junit.joinpath("release.xml").write_text("<testsuites>", encoding="utf-8")++ with pytest.raises(ReleaseEvidenceError):+ check_release_evidence(junit, workflow, root, scenario_root=scenarios)++@pytest.mark.parametrize(("reports", "selected", "verdict"),[@@ -114,8 +183,50 @@ def test_a_report_names_each_case_by_its_node_id(tmp_path: Path) -> None:assert reports.outcomes["windows-agent"] == {}+def test_release_evidence_uses_the_explicit_release_checkout_root(tmp_path: Path) -> None:+ root, scenarios, workflow, junit = _release_fixture(tmp_path)+ wrong_root = tmp_path / "primary-checkout"+ wrong_test = wrong_root / "tests" / "test_x.py"+ wrong_test.parent.mkdir(parents=True)+ wrong_test.write_text("def test_other():\n pass\n", encoding="utf-8")+ _write_release_report(junit, '<testcase classname="tests.test_x" name="test_case"/>')++ assert check_release_evidence(junit, workflow, root, scenario_root=scenarios) == {CASE: [CASE]}+ with pytest.raises(ReleaseEvidenceError, match="selects no covered"):+ check_release_evidence(junit, workflow, wrong_root, scenario_root=scenarios)++++ model_workflow = (WORKFLOWS / "model-hub-e2e.yml").read_text(encoding="utf-8")+ publish_workflow = (WORKFLOWS / "publish.yml").read_text(encoding="utf-8")++ assert "--release" in model_workflow+ assert "--workflow .github/workflows/model-hub-e2e.yml" in model_workflow+ assert "--pytest-root ." in model_workflow+ assert '--junitxml="$RUNNER_TEMP/model-hub-e2e-junit/model-hub-e2e.xml"' in model_workflow+ assert "--release" in publish_workflow+ assert "--workflow .github/workflows/publish.yml" in publish_workflow+ assert "(cd release-automation && python scripts/ci_scenario_evidence.py --release" in publish_workflow+ assert "--pytest-root ." in publish_workflow+ assert "scripts/ci_scenario_evidence.py" in publish_workflow+ assert "scripts/pytest_collection.py" in publish_workflow+ assert ".github/workflows/publish.yml" in publish_workflow+ assert "tests/scenarios/**/catalog.yaml" in publish_workflow+ assert "cd release-automation && python -m pytest tests/e2e/test_retired_updater_bridge.py" in publish_workflow+ assert '--junitxml="$RUNNER_TEMP/retired-updater-junit/retired-updater-bridge.xml"' in publish_workflow++ assert release_pytest_commands(WORKFLOWS / "model-hub-e2e.yml") == [+ ("-m", "e2e_model_hub", "tests/e2e", "-p", "no:cacheprovider")+ ]+ publish_commands = release_pytest_commands(WORKFLOWS / "publish.yml")+ assert publish_commands[1] == ("tests/e2e/test_retired_updater_bridge.py",)+ assert covered_test_evidence()[+ "tests/e2e/test_retired_updater_bridge.py::test_released_updater_replaces_companion_without_touching_user_data"+ ].rows == ["MUC-004"]++def test_release_gating_is_read_from_the_release_workflows() -> None:- """The Model Hub E2E and the release automation are the only CI that runs some covered rows' evidence."""+ """The Model Hub E2E and release automation select the expected covered rows."""commands = [args for name in RELEASE_WORKFLOWS for job in pytest_commands(WORKFLOWS / name).values() for args in job]evidence = covered_evidence()diff --git a/tests/test_release_verification.py b/tests/test_release_verification.pyindex dc68b15d8..817b06032 100644--- a/tests/test_release_verification.py+++ b/tests/test_release_verification.py@@ -419,9 +419,13 @@ def test_muc_004_retirement_gate_replays_from_workflow_checkout(tmp_path, tag, fgate = "TARGET_VERSION=" + step["run"].split("TARGET_VERSION=", 1)[1]automation = tmp_path / "release-automation"for name in _step(job, "Checkout release automation")["with"]["sparse-checkout"].splitlines():- target = automation / name- target.parent.mkdir(parents=True, exist_ok=True)- shutil.copy2(ROOT / name, target)+ sources = sorted(ROOT.glob(name)) if any(char in name for char in "*?[") else [ROOT / name]+ assert sources, f"sparse-checkout pattern has no repository matches: {name}"+ for source in sources:+ relative = source.relative_to(ROOT)+ target = automation / relative+ target.parent.mkdir(parents=True, exist_ok=True)+ shutil.copy2(source, target)binaries = tmp_path / "bin"binaries.mkdir()(binaries / "python").write_text(f"#!/bin/sh\nexec {shlex.quote(sys.executable)} \"$@\"\n")@@ -440,15 +444,18 @@ def test_muc_004_retirement_gate_replays_from_workflow_checkout(tmp_path, tag, fresult = subprocess.run(["bash", "-e", "-o", "pipefail", "-c", gate], cwd=tmp_path,env={**env, "RELEASE_TAG": tag, "PYTHONPATH": "",+ "RUNNER_TEMP": str(tmp_path / "runner-temp"),"PATH": f"{binaries}{os.pathsep}{os.environ['PATH']}"},capture_output=True, text=True, timeout=60,)- assert result.returncode == 0, result.stdout + result.stderrcollected = "tests/e2e/test_retired_updater_bridge.py::" in result.stdoutassert collected is forwardif forward:+ assert result.returncode != 0assert "1 skipped" in result.stdout+ assert "did not pass in the release run" in result.stdoutelse:+ assert result.returncode == 0, result.stdout + result.stderrassert "No forward Memory retirement upgrade" in result.stdout