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
ci: fail a covered scenario row whose evidence ran nowhere in CI (#2771)
Call White12b40718eb88
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.ymlindex d8bc68811..e23a9c812 100644--- a/.github/workflows/lint.yml+++ b/.github/workflows/lint.yml@@ -53,6 +53,9 @@ jobs:# An administrator can rename that requirement after this compatibility job# has landed; the job itself is a substantive removal contract, not a shim.runs-on: ubuntu-latest+ # Every pytest run in this job writes its junit report here (tests/conftest.py).+ env:+ AVIBE_CI_JUNIT_DIR: ${{ github.workspace }}/ci-junitsteps:- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5- name: Prepare hermetic UI asset placeholder@@ -76,6 +79,17 @@ jobs:pytest -q tests/test_memory_removal.py tests/test_admin_notifications.py \tests/test_message_facts_generic.py+ # Read by scenario-evidence, which proves each covered scenario row's+ # evidence ran (scripts/ci_scenario_evidence.py).+ - name: Upload junit reports+ if: always()+ uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6+ with:+ name: junit-${{ github.job }}-${{ strategy.job-index }}+ path: ci-junit/+ if-no-files-found: ignore+ retention-days: 7+ruff:needs: changesif: needs.changes.outputs.docs_only == 'false'@@ -269,6 +283,9 @@ jobs:# Preserve discovery, watchdogs and one-process-per-file isolation.shard: [0, 1, 2, 3, 4, 5, 6, 7]shard-total: [8]+ # Every pytest run in this job writes its junit report here (tests/conftest.py).+ env:+ AVIBE_CI_JUNIT_DIR: ${{ github.workspace }}/ci-junitsteps:- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5@@ -304,11 +321,22 @@ jobs:- name: Run unit tests shard ${{ matrix.shard }}/${{ matrix.shard-total }}run: bash scripts/ci_loopback_only.sh bash scripts/ci_unit_tests.sh "${{ matrix.shard }}" "${{ matrix.shard-total }}"+ # Read by scenario-evidence, which proves each covered scenario row's+ # evidence ran (scripts/ci_scenario_evidence.py).+ - name: Upload junit reports+ if: always()+ uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6+ with:+ name: junit-${{ github.job }}-${{ strategy.job-index }}+ path: ci-junit/+ if-no-files-found: ignore+ retention-days: 7+unit-tests:runs-on: ubuntu-latest# Keep UI validation in the existing required gate while allowing artifact# consumers to start as soon as their production bundle is built.- needs: [changes, unit-test-shards, ui-checks, ui-browser-checks]+ needs: [changes, unit-test-shards, scenario-evidence, ui-checks, ui-browser-checks]if: always()steps:- name: Verify unit test shards and UI checks@@ -316,6 +344,7 @@ jobs:SCOPE_RESULT: ${{ needs.changes.result }}DOCS_ONLY: ${{ needs.changes.outputs.docs_only }}UNIT_RESULT: ${{ needs['unit-test-shards'].result }}+ EVIDENCE_RESULT: ${{ needs['scenario-evidence'].result }}UI_RESULT: ${{ needs['ui-checks'].result }}BROWSER_RESULT: ${{ needs['ui-browser-checks'].result }}run: |@@ -328,7 +357,7 @@ jobs:false) expected="success" ;;*) echo "Missing or invalid change classification."; exit 1 ;;esac- for result in "$UNIT_RESULT" "$UI_RESULT" "$BROWSER_RESULT"; do+ for result in "$UNIT_RESULT" "$EVIDENCE_RESULT" "$UI_RESULT" "$BROWSER_RESULT"; doif [ "$result" != "$expected" ]; thenecho "Unit/UI checks finished with result: $result"exit 1@@ -336,10 +365,63 @@ jobs:doneecho "Unit/UI results match the classified scope (docs_only=$DOCS_ONLY)."+ # Every case a covered scenario row cites as evidence ran and passed in some+ # job, or a release workflow runs it (scripts/ci_scenario_evidence.py). It+ # waits for every job that writes junit; one that a path or event filter+ # skipped leaves no report, and its cases count as not run, never as failed.+ scenario-evidence:+ needs:+ - changes+ - unit-test-shards+ - memory-insight-contract+ - migration-release-guard+ - install-upgrade-shards+ - windows-model-hub+ - windows-control-ipc+ - windows-agent+ if: always() && needs.changes.outputs.docs_only == 'false'+ runs-on: ubuntu-latest+ timeout-minutes: 15+ steps:+ - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5++ - name: Prepare minimal UI asset placeholder+ run: |+ mkdir -p ui/dist+ printf '%s\n' '<!doctype html><html><body></body></html>' > ui/dist/index.html++ - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6+ with:+ python-version: "3.12"++ - name: Install pinned uv+ run: |+ python -m pip install --disable-pip-version-check --only-binary=:all: --no-deps uv==0.12.10++ - uses: actions/cache/restore@caa296126883cff596d87d8935842f9db880ef25 # v5+ with:+ path: ~/.cache/uv+ key: ${{ runner.os }}-${{ runner.arch }}-ci-uv-0.12.10-py3.12-${{ hashFiles('pyproject.toml', 'uv.lock') }}++ # Deciding what a workflow's pytest command selects collects test modules.+ - name: Install package and test deps+ run: uv pip install --system -e . --group dev++ - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8+ with:+ pattern: junit-*+ path: ci-junit++ - name: Check that covered scenario evidence ran+ run: python scripts/ci_scenario_evidence.py ci-junit+migration-release-guard:needs: changesif: needs.changes.outputs.docs_only == 'false'runs-on: ubuntu-latest+ # Every pytest run in this job writes its junit report here (tests/conftest.py).+ env:+ AVIBE_CI_JUNIT_DIR: ${{ github.workspace }}/ci-junitsteps:- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5with:@@ -384,6 +466,17 @@ jobs:exit 1fi+ # Read by scenario-evidence, which proves each covered scenario row's+ # evidence ran (scripts/ci_scenario_evidence.py).+ - name: Upload junit reports+ if: always()+ uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6+ with:+ name: junit-${{ github.job }}-${{ strategy.job-index }}+ path: ci-junit/+ if-no-files-found: ignore+ retention-days: 7+npm-wrapper:needs: changesif: needs.changes.outputs.docs_only == 'false'@@ -411,6 +504,9 @@ jobs:fail-fast: falsematrix:suite: [installer]+ # Every pytest run in this job writes its junit report here (tests/conftest.py).+ env:+ AVIBE_CI_JUNIT_DIR: ${{ github.workspace }}/ci-junitsteps:- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5@@ -479,6 +575,17 @@ jobs:tests/e2e/test_install_command.py \-v+ # Read by scenario-evidence, which proves each covered scenario row's+ # evidence ran (scripts/ci_scenario_evidence.py).+ - name: Upload junit reports+ if: always()+ uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6+ with:+ name: junit-${{ github.job }}-${{ strategy.job-index }}+ path: ci-junit/+ if-no-files-found: ignore+ retention-days: 7+install-upgrade-regression:runs-on: ubuntu-latestneeds: [changes, install-upgrade-shards]@@ -729,6 +836,9 @@ jobs:engine_platform: windows-amd64- runner: windows-11-armengine_platform: windows-arm64+ # Every pytest run in this job writes its junit report here (tests/conftest.py).+ env:+ AVIBE_CI_JUNIT_DIR: ${{ github.workspace }}/ci-junitsteps:- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5@@ -765,10 +875,24 @@ jobs:throw "The service acceptance did not run"}+ # Read by scenario-evidence, which proves each covered scenario row's+ # evidence ran (scripts/ci_scenario_evidence.py).+ - name: Upload junit reports+ if: always()+ uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6+ with:+ name: junit-${{ github.job }}-${{ strategy.job-index }}+ path: ci-junit/+ if-no-files-found: ignore+ retention-days: 7+windows-control-ipc:runs-on: windows-latestneeds: [changes, build-linux-artifacts]if: needs.changes.outputs.docs_only == 'false' && (github.event_name != 'pull_request' || needs.changes.outputs.windows_control_ipc == 'true')+ # Every pytest run in this job writes its junit report here (tests/conftest.py).+ env:+ AVIBE_CI_JUNIT_DIR: ${{ github.workspace }}/ci-junitsteps:- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5@@ -866,6 +990,17 @@ jobs:# text-mode descriptors without O_BINARY, st_ctime that means creation time).# Both runners use x64 Python: no win_arm64 wheel of cryptography exists, so# Avibe runs on Windows on Arm through x64 Python.++ # Read by scenario-evidence, which proves each covered scenario row's+ # evidence ran (scripts/ci_scenario_evidence.py).+ - name: Upload junit reports+ if: always()+ uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6+ with:+ name: junit-${{ github.job }}-${{ strategy.job-index }}+ path: ci-junit/+ if-no-files-found: ignore+ retention-days: 7windows-agent:name: windows-agent (${{ matrix.os }})runs-on: ${{ matrix.os }}@@ -876,6 +1011,9 @@ jobs:fail-fast: falsematrix:os: [windows-latest, windows-11-arm]+ # Every pytest run in this job writes its junit report here (tests/conftest.py).+ env:+ AVIBE_CI_JUNIT_DIR: ${{ github.workspace }}/ci-junitsteps:- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5@@ -951,3 +1089,14 @@ jobs:# this file on Windows.- name: Verify the watch worker's job objectrun: python -m pytest -q -ra tests/test_watch_worker.py++ # Read by scenario-evidence, which proves each covered scenario row's+ # evidence ran (scripts/ci_scenario_evidence.py).+ - name: Upload junit reports+ if: always()+ uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6+ with:+ name: junit-${{ github.job }}-${{ strategy.job-index }}+ path: ci-junit/+ if-no-files-found: ignore+ retention-days: 7diff --git a/scripts/ci_scenario_evidence.py b/scripts/ci_scenario_evidence.pynew file mode 100644index 000000000..ec91aa19d--- /dev/null+++ b/scripts/ci_scenario_evidence.py@@ -0,0 +1,306 @@+"""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+subdirectory is one job's ``junit-<job>-<index>`` artifact.+"""++from __future__ import annotations++import re+import shlex+import sys+import xml.etree.ElementTree as ElementTree+from collections.abc import Callable, Iterable+from dataclasses import dataclass, field+from pathlib import Path++import yaml++REPO_ROOT = Path(__file__).resolve().parents[1]+SCENARIO_ROOT = REPO_ROOT / "tests" / "scenarios"+WORKFLOWS = REPO_ROOT / ".github" / "workflows"+LINT_WORKFLOW = "lint.yml"+# The workflows a release needs green at its SHA (docs/release.md).+RELEASE_WORKFLOWS = ("model-hub-e2e.yml", "publish.yml")+# What scripts/ci_unit_tests.sh runs: every test file outside tests/e2e, without the integration marker.+UNIT_SHARD_ARGS = ("-m", "not integration", "--ignore=tests/e2e", "tests")+# The job this gate runs after on every event: its reports must all be there,+# or a broken report would read as every case "not run".+UNIT_SHARD_JOB = "unit-test-shards"+# Options that change what a pytest command selects, and those that take a value.+_SELECTING = {"-m", "-k", "-p", "-c", "-o", "--noconftest", "--ignore", "--deselect", "--rootdir"}+_VALUED = {"-m", "-k", "-p", "-c", "-o", "--ignore", "--deselect", "--rootdir"}+_SEPARATORS = re.compile(r"\s*(?:&&|\|\||;|\|)\s*")+++@dataclass+class Evidence:+ """One case a ``covered`` row cites, the rows citing it, and what CI recorded for it."""++ citation: str+ rows: list[str]+ skips: list[str] = field(default_factory=list)+++def covered_evidence(scenario_root: Path = SCENARIO_ROOT) -> dict[str, Evidence]:+ """Every pytest case a ``covered`` row cites under ``test``, by citation."""++ 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")+ for citation in cited if isinstance(cited, list) else [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."""++ file, _, name = citation.partition("::")+ node_file, _, rest = nodeid.partition("::")+ if node_file != file:+ return False+ base, bracket, param = name.partition("[")+ node_base, node_bracket, node_param = rest.partition("[")+ parts, node_parts = base.split("::"), node_base.split("::")+ named = node_parts == parts or (len(parts) == 1 and node_parts[-1] == parts[0])+ return named and (not bracket or node_bracket + node_param == bracket + param)+++def _nodeid(classname: str, name: str, repo_root: Path) -> str | None:+ """The node id junit's ``classname`` and ``name`` came from; None for a file outside the repository."""++ parts = classname.split(".")+ for end in range(len(parts), 0, -1):+ path = "/".join(parts[:end]) + ".py"+ if (repo_root / path).is_file():+ return "::".join([path, *parts[end:], name])+ return None+++@dataclass+class Reports:+ """What each job's junit artifacts recorded, and how many artifacts each left."""++ outcomes: dict[str, dict[str, tuple[str, str]]] = field(default_factory=dict)+ artifacts: dict[str, int] = field(default_factory=dict)++ def by_file(self) -> dict[str, list[tuple[str, str, str]]]:+ indexed: dict[str, list[tuple[str, str, str]]] = {}+ for job in self.outcomes.values():+ for nodeid, (outcome, message) in job.items():+ indexed.setdefault(nodeid.partition("::")[0], []).append((nodeid, outcome, message))+ return indexed+++def read_reports(junit_dir: Path, repo_root: Path = REPO_ROOT) -> Reports:+ """Each job's outcomes, ``{nodeid: (outcome, message)}``, from its ``junit-<job>-<index>`` artifacts."""++ reports = Reports()+ for artifact in sorted(path for path in junit_dir.iterdir() if path.is_dir() and path.name.startswith("junit-")):+ job = artifact.name.removeprefix("junit-").rsplit("-", 1)[0]+ reports.artifacts[job] = reports.artifacts.get(job, 0) + 1+ outcomes = reports.outcomes.setdefault(job, {})+ for report in sorted(artifact.rglob("*.xml")):+ for case in ElementTree.parse(report).getroot().iter("testcase"):+ nodeid = _nodeid(case.get("classname", ""), case.get("name", ""), repo_root)+ if nodeid is None:+ continue+ skipped = case.find("skipped")+ if case.find("failure") is not None or case.find("error") is not None:+ outcome = ("failed", "")+ elif skipped is not None:+ outcome = ("skipped", skipped.get("message", ""))+ else:+ outcome = ("passed", "")+ # One pass anywhere in the job is the job's answer.+ if outcomes.get(nodeid, ("",))[0] != "passed":+ outcomes[nodeid] = outcome+ return reports+++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."""++ matrix = (job.get("strategy") or {}).get("matrix")+ if not isinstance(matrix, dict):+ return 1+ size = 1+ lists = [value for key, value in matrix.items() if key not in ("include", "exclude") and isinstance(value, list)]+ for value in lists:+ size *= len(value)+ if not lists and isinstance(matrix.get("include"), list):+ size = len(matrix["include"])+ return max(size, 1)+++def workflow_jobs(workflow: Path) -> dict[str, dict]:+ return yaml.safe_load(workflow.read_text(encoding="utf-8")).get("jobs") or {}+++def pytest_commands(workflow: Path) -> dict[str, list[tuple[str, ...]]]:+ """Each job's pytest commands, as the arguments that decide what they select.++ A command whose arguments depend on the shell (``$``, a backtick) is left+ out: its selection cannot be known from the file.+ """++ jobs = workflow_jobs(workflow)+ commands: dict[str, list[tuple[str, ...]]] = {}+ for job_id, job in jobs.items():+ for step in job.get("steps") or []:+ script = re.sub(r"[\\`]\r?\n", " ", step.get("run") or "")+ if "scripts/ci_unit_tests.sh" in script:+ commands.setdefault(job_id, []).append(UNIT_SHARD_ARGS)+ continue+ for line in script.splitlines():+ for command in _SEPARATORS.split(line):+ try:+ tokens = [token.strip("()") for token in shlex.split(command)]+ except ValueError:+ continue+ if "pytest" not in tokens:+ continue+ args = _selecting_args(tokens[tokens.index("pytest") + 1 :])+ if args is not None:+ commands.setdefault(job_id, []).append(args)+ return commands+++def _selecting_args(tokens: list[str]) -> tuple[str, ...] | None:+ selecting: list[str] = []+ take_value = False+ for token in tokens:+ if take_value:+ selecting.append(token)+ take_value = False+ elif token.split("=", 1)[0] in _SELECTING:+ selecting.append(token)+ take_value = token in _VALUED+ elif token.startswith("tests"):+ selecting.append(token)+ if any("$" in token or "`" in token for token in selecting) or not any(token.startswith("tests") for token in selecting):+ return None+ return tuple(selecting)+++def judge(+ evidence: dict[str, Evidence],+ reports: Reports,+ lint_commands: dict[str, list[tuple[str, ...]]],+ lint_runs: dict[str, int],+ release_commands: list[tuple[str, ...]],+ select: Callable[[tuple[str, ...]], Iterable[str]],+) -> tuple[list[str], dict[str, list[str]]]:+ """The problems with ``evidence`` given what CI reported, and which cases were release-gated or not run.++ A ``lint.yml`` job counts as reported only when every run of its matrix+ left an artifact (``lint_runs``): a run that left none -- skipped by its+ path or event filter, or gone before its upload -- says nothing about the+ cases it would have run. The unit shards are the exception: this gate runs+ whenever they do, so a missing shard report is itself a problem. ``select`` returns the node ids a command's+ arguments select; it is only asked about commands that could account for a+ case no report showed passing.+ """++ expected = lint_runs.get(UNIT_SHARD_JOB, 1)+ if reports.artifacts.get(UNIT_SHARD_JOB, 0) < expected:+ return [f"{UNIT_SHARD_JOB} left {reports.artifacts.get(UNIT_SHARD_JOB, 0)} of {expected} junit reports"], {}+ by_file = reports.by_file()+ pending: list[Evidence] = []+ for case in evidence.values():+ outcomes = [+ (outcome, message)+ for nodeid, outcome, message in by_file.get(case.citation.partition("::")[0], [])+ if names_case(case.citation, nodeid)+ ]+ if any(outcome == "passed" for outcome, _ in outcomes):+ continue+ case.skips = sorted({message or outcome for outcome, message in outcomes})+ pending.append(case)+ accounted: dict[str, list[str]] = {"release-gated": [], "not run": []}+ if not pending:+ return [], accounted+ selections: dict[tuple[str, ...], list[str]] = {}++ def selects(args: tuple[str, ...], citation: str) -> bool:+ if args not in selections:+ selections[args] = list(select(args))+ return any(names_case(citation, nodeid) for nodeid in selections[args])++ unreported = [+ args+ for job, commands in lint_commands.items()+ if reports.artifacts.get(job, 0) < lint_runs.get(job, 1)+ for args in commands+ ]+ problems: list[str] = []+ for case in pending:+ rows = ", ".join(case.rows)+ if any(selects(args, case.citation) for args in release_commands):+ accounted["release-gated"].append(case.citation)+ elif any(selects(args, case.citation) for args in unreported):+ accounted["not run"].append(case.citation)+ elif case.skips:+ problems.append(f"{rows}: {case.citation} was skipped everywhere it ran ({'; '.join(case.skips)})")+ else:+ problems.append(f"{rows}: {case.citation} was collected by no CI job that ran, and no release runs it")+ return problems, accounted+++def main(argv: list[str]) -> int:+ from scripts import pytest_collection++ (junit_dir,) = argv+ reports = read_reports(Path(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]+ evidence = covered_evidence()+ problems, accounted = judge(+ evidence,+ reports,+ lint_commands,+ lint_runs,+ release_commands,+ lambda args: [entry["nodeid"] for entry in pytest_collection.collect(list(args))],+ )+ print(f"Read reports from {len(reports.outcomes)} job(s): {', '.join(sorted(reports.outcomes)) or 'none'}.")+ print(f"{len(evidence)} case(s) evidence covered rows; {len(problems)} never ran.")+ for kind, citations in accounted.items():+ for citation in citations:+ print(f" {kind}: {citation}")+ for problem in problems:+ print(f"::error::{problem}")+ return 1 if problems else 0+++if __name__ == "__main__":+ sys.path.insert(0, str(REPO_ROOT))+ sys.exit(main(sys.argv[1:]))diff --git a/scripts/pytest_collection.py b/scripts/pytest_collection.pynew file mode 100644index 000000000..84dc4ac2c--- /dev/null+++ b/scripts/pytest_collection.py@@ -0,0 +1,94 @@+"""What pytest itself collects for a set of arguments, without running anything.++Two scenario-catalog gates ask pytest rather than reading source: the citation+check (``tests/scenarios/test_catalog_citations.py``) asks which cases a cited+file holds, and the evidence gate (``scripts/ci_scenario_evidence.py``) asks+which cases a workflow's pytest command would run. Both get pytest's own answer,+selection and deselection included, from one collection-only run in a child+process with the conftest files that apply where it runs: a nested+``pytest.main`` would share the caller's modules and plugins.+"""++from __future__ import annotations++import json+import os+import subprocess+import sys+import tempfile+from pathlib import Path++REPO_ROOT = Path(__file__).resolve().parents[1]+# One collection of every file the catalogs cite takes about a minute in CI; the bound only stops a hang.+COLLECTION_TIMEOUT_SECONDS = 300+++class _Recorder:+ """A pytest plugin that writes what a collection-only run collected, as JSON."""++ def __init__(self, out: str) -> None:+ self.out = out++ def pytest_collection_finish(self, session) -> None:+ cases = []+ for item in session.items:+ function = getattr(item, "function", None)+ cases.append(+ {+ "nodeid": item.nodeid,+ "doc": (function.__doc__ if function is not None else None) or "",+ "skipped": _declares_skip(item),+ }+ )+ Path(self.out).write_text(json.dumps(cases), encoding="utf-8")+++def _declares_skip(item) -> bool:+ """Whether the case, its class, its module or its parameter set declares a skip.++ Only a declared ``skip``: one a hook adds while collecting, such as the+ e2e suites' opt-in, depends on the run's options as ``skipif`` depends on+ the environment.+ """++ function, owner, module = (getattr(item, name, None) for name in ("function", "cls", "module"))+ marks = list(getattr(getattr(item, "callspec", None), "marks", None) or [])+ for target in (function, owner, module):+ declared = getattr(target, "pytestmark", None) or []+ marks.extend(declared if isinstance(declared, (list, tuple)) else [declared])+ return any(getattr(mark, "name", None) == "skip" for mark in marks) or any(+ getattr(target, "__unittest_skip__", False) for target in (function, owner)+ )+++def collect(args: list[str], cwd: Path = REPO_ROOT) -> list[dict]:+ """Each case ``pytest --collect-only <args>`` collects from ``cwd``: its node id, docstring and declared skip."""++ with tempfile.TemporaryDirectory() as directory:+ out = Path(directory) / "collected.json"+ result = subprocess.run(+ [sys.executable, "-c", "from scripts.pytest_collection import _main\n_main()", str(out), *args],+ cwd=cwd,+ # Without the caller's PYTEST_ADDOPTS, whose selection would drop cases,+ # 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")])),+ },+ capture_output=True,+ text=True,+ timeout=COLLECTION_TIMEOUT_SECONDS,+ )+ if result.returncode != 0 or not out.is_file():+ raise RuntimeError(+ f"pytest could not collect {' '.join(args)} (exit {result.returncode}):\n"+ f"{result.stdout[-4000:]}{result.stderr[-4000:]}"+ )+ return json.loads(out.read_text(encoding="utf-8"))+++def _main() -> None:+ import pytest++ out, *args = sys.argv[1:]+ sys.exit(int(pytest.main(["--collect-only", "-q", "-p", "no:cacheprovider", "-o", "addopts=", *args], plugins=[_Recorder(out)])))diff --git a/standards/scenario-testing/STANDARD.md b/standards/scenario-testing/STANDARD.mdindex 8b43df465..ed0faddd9 100644--- a/standards/scenario-testing/STANDARD.md+++ b/standards/scenario-testing/STANDARD.md@@ -206,7 +206,11 @@ pytest's for Python, vitest's for UI — so a case the runner would not collect,such as one in a suppressed or deselected class, is not evidence. A pytestevidence case must also name the citing row's ID in its docstring; a case thatproves several rows names each of them. Then a case written for something else-cannot be attached to a row unnoticed.+cannot be attached to a row unnoticed. Finally, the evidence of a `covered` row+must run: every case it cites passes in some CI job's run, or a workflow a+release requires runs it. A case skipped wherever it ran — by a condition that+always holds in CI, an imperative skip, or a deselecting hook — does not make+its row `covered`.## 5. Harness Design Rulesdiff --git a/tests/conftest.py b/tests/conftest.pyindex 7353ae29d..db5ddfabe 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -59,6 +59,7 @@ import subprocessimport sysimport tempfileimport threading+import timeimport tracebackimport unittestimport urllib.parse@@ -165,6 +166,8 @@ os.environ.update(_home_env(_SESSION_HOME))Path.home = classmethod(lambda cls: _SESSION_HOME)+# Before the junitxml plugin reads its report path.[email protected](tryfirst=True)def pytest_configure(config):# A desktop caller is also whoever runs from a private tree's interpreter,# which no environment clearing undoes: every stop and restart under test@@ -175,6 +178,12 @@ def pytest_configure(config):raise pytest.UsageError(f"{sys.executable} is a desktop Runtime's private interpreter; run the tests with another Python")+ # In CI every pytest run reports what it ran, one file per run, so that+ # scripts/ci_scenario_evidence.py can tell which cited cases ran.+ junit_dir = os.environ.get("AVIBE_CI_JUNIT_DIR")+ if junit_dir and getattr(config.option, "xmlpath", "") is None:+ os.makedirs(junit_dir, exist_ok=True)+ config.option.xmlpath = os.path.join(junit_dir, f"{os.getpid()}-{time.monotonic_ns()}.xml")# Every process a `reap_processes` test starts ends with it (tests/process_reaper.py):diff --git a/tests/scenarios/test_catalog_citations.py b/tests/scenarios/test_catalog_citations.pyindex 182f70313..e1c9447f8 100644--- a/tests/scenarios/test_catalog_citations.py+++ b/tests/scenarios/test_catalog_citations.py@@ -33,17 +33,13 @@ deselecting hook, a test defined in a branch not taken.A cited Python file must be one pytest's default discovery collects(``test_*.py`` or ``*_test.py``). Conditional skips (``skipif``) depend on the-environment, and whether a case actually ran belongs to CI's results (#2565).+environment; whether each case a ``covered`` row cites actually ran is decided+from CI's own results by ``scripts/ci_scenario_evidence.py``."""from __future__ import annotations-import json-import osimport re-import subprocess-import sys-import tempfilefrom dataclasses import dataclassfrom functools import cachefrom pathlib import Path@@ -51,14 +47,14 @@ from pathlib import Pathimport pytestimport yaml+from scripts import pytest_collection+REPO_ROOT = Path(__file__).resolve().parents[2]SCENARIO_ROOT = REPO_ROOT / "tests" / "scenarios"_UI_SUFFIXES = {".ts", ".tsx", ".mts", ".mjs"}_POINTER_KEYS = ("related_tests", "supporting_tests")# pytest's default ``python_files``, which this repository does not override._DISCOVERED = re.compile(r"(test_.*|.*_test)\.py")-# One collection of every cited file runs in about 20 s; the bound only stops a hang.-_COLLECTION_TIMEOUT_SECONDS = 240@dataclass(frozen=True)@@ -71,50 +67,6 @@ class _Case:skipped: bool-class _Recorder:- """A pytest plugin that writes what a collection-only run collected, as JSON."""-- def __init__(self, out: str) -> None:- self.out = out-- def pytest_collection_finish(self, session: pytest.Session) -> None:- cases = []- for item in session.items:- function = getattr(item, "function", None)- cases.append(- {- "nodeid": item.nodeid,- "doc": (function.__doc__ if function is not None else None) or "",- "skipped": _declares_skip(item),- }- )- Path(self.out).write_text(json.dumps(cases), encoding="utf-8")---def _declares_skip(item: pytest.Item) -> bool:- """Whether the case, its class, its module or its parameter set declares a skip.-- Only a declared ``skip``: one a hook adds while collecting, such as the- e2e suites' opt-in, depends on the run's options as ``skipif`` depends on- the environment.- """-- function, owner, module = (getattr(item, name, None) for name in ("function", "cls", "module"))- marks = list(getattr(getattr(item, "callspec", None), "marks", None) or [])- for target in (function, owner, module):- declared = getattr(target, "pytestmark", None) or []- marks.extend(declared if isinstance(declared, (list, tuple)) else [declared])- return any(getattr(mark, "name", None) == "skip" for mark in marks) or any(- getattr(target, "__unittest_skip__", False) for target in (function, owner)- )---def _collect(out: str, files: list[str]) -> int:- """Collect ``files`` as CI does, without running them, and record each case in ``out``."""-- return int(pytest.main(["--collect-only", "-q", "-p", "no:cacheprovider", "-o", "addopts=", *files], plugins=[_Recorder(out)]))--def _catalogs() -> list[Path]:catalogs = sorted(SCENARIO_ROOT.glob("*/catalog.yaml"))assert catalogs, f"no scenario catalogs under {SCENARIO_ROOT}"@@ -162,40 +114,10 @@ def _citations(row: dict) -> tuple[list[tuple[str, object]], list[str]]:def _collect_cases(files: list[str], cwd: Path) -> dict[str, list[_Case]]:- """Every case pytest collects from ``files``, relative to ``cwd``, by file.+ """Every case pytest collects from ``files``, relative to ``cwd``, by file."""- One collection-only run in a child process, with the conftest files that- apply there: a nested ``pytest.main`` would share this session's modules and- plugins.- """-- with tempfile.TemporaryDirectory() as directory:- out = Path(directory) / "collected.json"- result = subprocess.run(- [- sys.executable,- "-c",- "import sys\nfrom tests.scenarios.test_catalog_citations import _collect\n"- "sys.exit(_collect(sys.argv[1], sys.argv[2:]))",- str(out),- *files,- ],- cwd=cwd,- # Without the caller's PYTEST_ADDOPTS, whose selection would drop cited cases.- env={- **{name: value for name, value in os.environ.items() if name != "PYTEST_ADDOPTS"},- "PYTHONPATH": os.pathsep.join(filter(None, [str(REPO_ROOT), os.environ.get("PYTHONPATH")])),- },- capture_output=True,- text=True,- timeout=_COLLECTION_TIMEOUT_SECONDS,- )- assert result.returncode == 0 and out.is_file(), (- f"pytest could not collect the cited files (exit {result.returncode}):\n{result.stdout[-4000:]}{result.stderr[-4000:]}"- )- recorded = json.loads(out.read_text(encoding="utf-8"))cases: dict[str, list[_Case]] = {file: [] for file in files}- for entry in recorded:+ for entry in pytest_collection.collect(files, cwd):file, _, rest = entry["nodeid"].partition("::")base, bracket, param = rest.partition("[")cases.setdefault(file, []).append(diff --git a/tests/test_ci_scenario_evidence.py b/tests/test_ci_scenario_evidence.pynew file mode 100644index 000000000..03f087d68--- /dev/null+++ b/tests/test_ci_scenario_evidence.py@@ -0,0 +1,131 @@+"""The scenario evidence gate: a covered row's evidence ran in CI, or a release runs it (scripts/ci_scenario_evidence.py)."""++from __future__ import annotations++from pathlib import Path++import pytest++from scripts import pytest_collection+from scripts.ci_scenario_evidence import (+ RELEASE_WORKFLOWS,+ UNIT_SHARD_JOB,+ WORKFLOWS,+ Evidence,+ Reports,+ covered_evidence,+ judge,+ pytest_commands,+ read_reports,+)++CASE = "tests/test_x.py::test_case"+WINDOWS = ("tests/test_x.py", "-k", "windows")+RELEASE = ("-m", "release", "tests/e2e")+++def _reports(**jobs: dict[str, tuple[str, str]]) -> Reports:+ reports = Reports(outcomes={UNIT_SHARD_JOB: {}}, artifacts={UNIT_SHARD_JOB: 8})+ for job, outcomes in jobs.items():+ job = job.replace("_", "-")+ reports.outcomes[job] = outcomes+ reports.artifacts[job] = reports.artifacts.get(job, 0) or 1+ return reports+++ ("reports", "selected", "verdict"),+ [+ pytest.param(+ _reports(unit_test_shards={f"{CASE}[linux]": ("skipped", "not on Linux")}, windows_control_ipc={f"{CASE}[win]": ("passed", "")}),+ {},+ None,+ id="passed-on-one-platform",+ ),+ pytest.param(+ _reports(unit_test_shards={CASE: ("skipped", "not on Linux")}),+ {WINDOWS: [CASE]},+ "not run",+ id="its-other-job-was-path-skipped",+ ),+ pytest.param(+ _reports(unit_test_shards={CASE: ("skipped", "needs a Codex binary")}, windows_control_ipc={CASE: ("skipped", "needs a Codex binary")}),+ {WINDOWS: [CASE]},+ "skipped everywhere it ran (needs a Codex binary)",+ id="skipped-everywhere-it-ran",+ ),+ pytest.param(_reports(), {RELEASE: [CASE]}, "release-gated", id="a-release-runs-it"),+ pytest.param(_reports(), {}, "collected by no CI job that ran", id="no-job-runs-it"),+ pytest.param(+ Reports(outcomes={UNIT_SHARD_JOB: {}}, artifacts={UNIT_SHARD_JOB: 7}),+ {},+ f"{UNIT_SHARD_JOB} left 7 of 8 junit reports",+ id="a-unit-shard-left-no-report",+ ),+ ],+)+def test_only_evidence_skipped_or_absent_everywhere_it_could_have_run_fails(reports, selected, verdict) -> None:+ """A job that left no report, such as one its path filter skipped, says nothing about its cases.++ The required gate must not turn red because a job did not run on this+ change: such a job's cases are "not run", and a case fails only when it+ was skipped, or absent, wherever CI did run and no release runs it.+ """++ lint_commands = {UNIT_SHARD_JOB: [("tests",)], "windows-control-ipc": [WINDOWS]}+ lint_runs = {UNIT_SHARD_JOB: 8, "windows-control-ipc": 1}+ if verdict == "not run":+ reports.artifacts.pop("windows-control-ipc", None)+ problems, accounted = judge(+ {CASE: Evidence(CASE, ["ROW-1"])},+ reports,+ lint_commands,+ lint_runs,+ [RELEASE],+ lambda args: selected.get(args, []),+ )++ if verdict is None:+ assert (problems, accounted) == ([], {"release-gated": [], "not run": []})+ elif verdict in ("not run", "release-gated"):+ assert problems == [] and accounted[verdict] == [CASE]+ else:+ (problem,) = problems+ assert verdict in problem+++def test_a_report_names_each_case_by_its_node_id(tmp_path: Path) -> None:+ (tmp_path / "tests").mkdir()+ (tmp_path / "tests" / "test_x.py").write_text("", encoding="utf-8")+ for artifact, body in (+ ("junit-unit-test-shards-0", '<testcase classname="tests.test_x.TestA" name="test_m[a b]"><skipped message="off"/></testcase>'),+ ("junit-unit-test-shards-1", '<testcase classname="tests.test_x.TestA" name="test_m[a b]"/>'),+ ("junit-windows-agent-0", '<testcase classname="test_inner" name="test_elsewhere"/>'),+ ):+ (tmp_path / "junit" / artifact).mkdir(parents=True)+ (tmp_path / "junit" / artifact / "1.xml").write_text(f"<testsuites><testsuite>{body}</testsuite></testsuites>", encoding="utf-8")++ reports = read_reports(tmp_path / "junit", tmp_path)++ assert reports.artifacts == {"unit-test-shards": 2, "windows-agent": 1}+ assert reports.outcomes["unit-test-shards"] == {"tests/test_x.py::TestA::test_m[a b]": ("passed", "")}+ # A case outside the repository, such as a test's own inner pytest run, is no evidence.+ assert reports.outcomes["windows-agent"] == {}+++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."""++ commands = [args for name in RELEASE_WORKFLOWS for job in pytest_commands(WORKFLOWS / name).values() for args in job]+ evidence = covered_evidence()+ gated = {+ citation+ for args in commands+ for nodeid in (entry["nodeid"] for entry in pytest_collection.collect(list(args)))+ for citation in evidence+ if nodeid.partition("[")[0] in (citation, citation.partition("[")[0])+ }++ assert evidence["tests/e2e/test_model_hub_mock_upstream.py::test_mh_routing_001_mock_model_errors_are_request_scoped_and_inventory_independent"].rows == ["MH-ROUTING-001"]+ assert "tests/e2e/test_model_hub_mock_upstream.py::test_mh_routing_001_mock_model_errors_are_request_scoped_and_inventory_independent" in gated+ assert "tests/e2e/test_retired_updater_bridge.py::test_released_updater_replaces_companion_without_touching_user_data" in gated