diff --git a/src/chemenu/evals/baseline.py b/src/chemenu/evals/baseline.py new file mode 100644 index 0000000..51890c8 --- /dev/null +++ b/src/chemenu/evals/baseline.py @@ -0,0 +1,111 @@ +"""Read the recorded state of an eval set from a git ref.""" + +import io +import os +import shutil +import subprocess +import tarfile +import tempfile +from pathlib import Path +from typing import Final + +from chemenu.evals.compare import Baseline, BaselineCase, input_key +from chemenu.evals.loader import EvalSetError, RecordedResponses, read_yaml +from chemenu.evals.model import ResponseError + +# Variables that pin git to a repository; set by hooks and `git rebase --exec`. +GIT_REPO_ENV: Final = ( + "GIT_DIR", + "GIT_WORK_TREE", + "GIT_INDEX_FILE", + "GIT_COMMON_DIR", + "GIT_OBJECT_DIRECTORY", + "GIT_ALTERNATE_OBJECT_DIRECTORIES", + "GIT_NAMESPACE", + "GIT_PREFIX", +) + + +class BaselineError(Exception): + """git missing, set outside a repository, or unknown ref; CLI exit 2.""" + + +def _run(git: str, *args: str) -> subprocess.CompletedProcess[bytes]: + env = {k: v for k, v in os.environ.items() if k not in GIT_REPO_ENV} + try: + return subprocess.run( # noqa: S603 # list argv, no shell, git resolved by shutil.which + [git, *args], capture_output=True, check=False, env=env + ) + except OSError as exc: + raise BaselineError(f"cannot run git: {exc}") from exc + + +def _one_line(proc: subprocess.CompletedProcess[bytes]) -> str: + text = " ".join(proc.stderr.decode("utf-8", "replace").split()) + return text or f"git exited with status {proc.returncode}" + + +def load_baseline(set_dir: Path, ref: str) -> Baseline: + git = shutil.which("git") + if git is None: + raise BaselineError("git not found on PATH") + + proc = _run(git, "-C", str(set_dir), "rev-parse", "--show-toplevel") + if proc.returncode != 0: + raise BaselineError(f"{set_dir}: not inside a git repository: {_one_line(proc)}") + top = proc.stdout.decode("utf-8", "replace").rstrip("\n") + + proc = _run( + git, "-C", top, "rev-parse", "--verify", "--quiet", "--end-of-options", f"{ref}^{{commit}}" + ) + commit = proc.stdout.decode("ascii", "replace").strip() + if proc.returncode != 0 or not commit: + raise BaselineError(f"unknown ref {ref!r}") + + try: + rel = set_dir.resolve().relative_to(Path(top).resolve()).as_posix() + except ValueError: + raise BaselineError(f"{set_dir}: not inside repository {top}") from None + rel = "" if rel == "." else rel + obj = f"{commit}:{rel}" + + if _run(git, "-C", top, "rev-parse", "--verify", "--quiet", obj).returncode != 0: + return Baseline(ref=ref, commit=commit, cases=None) + + proc = _run(git, "-C", top, "archive", "--format=tar", obj) + if proc.returncode != 0: + raise BaselineError(f"cannot read {set_dir} at {ref!r}: {_one_line(proc)}") + + try: + with tempfile.TemporaryDirectory() as tmp_name: + tmp = Path(tmp_name) + with tarfile.open(fileobj=io.BytesIO(proc.stdout)) as archive: + archive.extractall(tmp, filter="data") + return Baseline(ref=ref, commit=commit, cases=_read_cases(tmp)) + except (tarfile.TarError, OSError) as exc: + raise BaselineError(f"cannot unpack {set_dir} at {ref!r}: {exc}") from exc + + +def _read_cases(root: Path) -> dict[str, BaselineCase]: + responses = RecordedResponses(root / "recorded") + cases: dict[str, BaselineCase] = {} + cases_dir = root / "cases" + if not cases_dir.is_dir(): + return cases + for path in sorted(cases_dir.glob("*.yaml"), key=lambda p: p.stem): + case_id = path.stem + key: str | None + try: + data = read_yaml(path) + key = input_key(data["input"]) if "input" in data else None + except EvalSetError: + key = None + unreadable = False + try: + response = responses.response_for(case_id) + except ResponseError: + response, unreadable = None, True + cases[case_id] = BaselineCase( + case_id=case_id, input_key=key, response=response, response_unreadable=unreadable + ) + return cases diff --git a/tests/evals/conftest.py b/tests/evals/conftest.py new file mode 100644 index 0000000..d2c7fe5 --- /dev/null +++ b/tests/evals/conftest.py @@ -0,0 +1,16 @@ +import pytest + +from chemenu.evals.baseline import GIT_REPO_ENV + + +@pytest.fixture(autouse=True) +def _isolated_git(monkeypatch: pytest.MonkeyPatch) -> None: + """Keep git in tests away from the repository running them. + + `git rebase --exec` and hooks export GIT_DIR; without this, `git init` and + `git commit` in a test would act on the checkout itself. + """ + for name in GIT_REPO_ENV: + monkeypatch.delenv(name, raising=False) + monkeypatch.setenv("GIT_CONFIG_GLOBAL", "/dev/null") + monkeypatch.setenv("GIT_CONFIG_NOSYSTEM", "1") diff --git a/tests/evals/test_baseline_git.py b/tests/evals/test_baseline_git.py new file mode 100644 index 0000000..9d22521 --- /dev/null +++ b/tests/evals/test_baseline_git.py @@ -0,0 +1,149 @@ +"""load_baseline against real git repositories in tmp_path.""" + +import subprocess +from pathlib import Path + +import pytest + +from chemenu.evals.baseline import BaselineError, load_baseline +from chemenu.evals.compare import input_key + +GIT = [ + "git", + "-c", + "user.name=t", + "-c", + "user.email=t@example.invalid", + "-c", + "commit.gpgsign=false", +] + + +def git(repo: Path, *args: str) -> str: + result = subprocess.run( # noqa: S603 + [*GIT, "-C", str(repo), *args], capture_output=True, text=True, check=True + ) + return result.stdout.strip() + + +def write_set(repo: Path, value: int, response: str) -> Path: + set_dir = repo / "evals" / "demo" + (set_dir / "cases").mkdir(parents=True, exist_ok=True) + (set_dir / "recorded").mkdir(exist_ok=True) + (set_dir / "eval.yaml").write_text("name: demo\n") + (set_dir / "cases" / "a.yaml").write_text(f"input: {{x: {value}}}\n") + (set_dir / "recorded" / "a.json").write_text(response) + return set_dir + + +def commit(repo: Path, message: str) -> str: + git(repo, "add", "-A") + git(repo, "commit", "-q", "-m", message) + return git(repo, "rev-parse", "HEAD") + + +@pytest.fixture +def repo(tmp_path: Path) -> Path: + git(tmp_path, "init", "-q") + return tmp_path + + +def test_reads_cases_and_responses_at_ref(repo: Path) -> None: + set_dir = write_set(repo, 1, '{"v": 1}') + sha = commit(repo, "one") + git(repo, "tag", "v1") + write_set(repo, 2, '{"v": 2}') + commit(repo, "two") + write_set(repo, 3, '{"v": 3}') + + for ref in ("HEAD~1", "v1", sha): + baseline = load_baseline(set_dir, ref) + assert baseline.ref == ref + assert baseline.commit == sha + assert baseline.cases is not None + case = baseline.cases["a"] + assert case.case_id == "a" + assert case.input_key == input_key({"x": 1}) + assert case.response == '{"v": 1}' + + +def test_set_missing_at_ref_gives_none(repo: Path) -> None: + (repo / "README").write_text("x") + first = commit(repo, "one") + set_dir = write_set(repo, 1, "{}") + commit(repo, "two") + baseline = load_baseline(set_dir, first) + assert baseline.cases is None + assert baseline.commit == first + + +def test_unreadable_case_has_no_input_key(repo: Path) -> None: + set_dir = write_set(repo, 1, "{}") + (set_dir / "cases" / "bad.yaml").write_text("input: [unclosed\n") + (set_dir / "cases" / "noinput.yaml").write_text("expect: {}\n") + (set_dir / "recorded" / "noinput.json").write_bytes(b"\xff\xfe\x00{") + commit(repo, "one") + baseline = load_baseline(set_dir, "HEAD") + assert baseline.cases is not None + assert baseline.cases["bad"].input_key is None + assert baseline.cases["bad"].response is None + assert baseline.cases["noinput"].input_key is None + assert baseline.cases["noinput"].response_unreadable + assert not baseline.cases["a"].response_unreadable + assert baseline.cases["a"].input_key == input_key({"x": 1}) + + +@pytest.mark.parametrize("ref", ["nope", "--output=x"]) +def test_unknown_ref_raises(repo: Path, ref: str) -> None: + set_dir = write_set(repo, 1, "{}") + commit(repo, "one") + before = sorted(p.name for p in repo.iterdir()) + with pytest.raises(BaselineError): + load_baseline(set_dir, ref) + assert sorted(p.name for p in repo.iterdir()) == before + assert not (repo / "x").exists() + + +def test_outside_repository_raises(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("GIT_CEILING_DIRECTORIES", str(tmp_path)) + set_dir = write_set(tmp_path, 1, "{}") + with pytest.raises(BaselineError): + load_baseline(set_dir, "HEAD") + + +def test_working_tree_untouched(repo: Path) -> None: + set_dir = write_set(repo, 1, '{"v": 1}') + commit(repo, "one") + write_set(repo, 2, '{"v": 2}') + status = git(repo, "status", "--porcelain") + files = sorted(p for p in repo.rglob("*") if ".git" not in p.parts) + content = (set_dir / "recorded" / "a.json").read_text() + load_baseline(set_dir, "HEAD") + assert git(repo, "status", "--porcelain") == status + assert sorted(p for p in repo.rglob("*") if ".git" not in p.parts) == files + assert (set_dir / "recorded" / "a.json").read_text() == content + + +def test_ignores_inherited_git_dir( + repo: Path, tmp_path_factory: pytest.TempPathFactory, monkeypatch: pytest.MonkeyPatch +) -> None: + set_dir = write_set(repo, 1, '{"v": 1}') + sha = commit(repo, "one") + other = tmp_path_factory.mktemp("other") + git(other, "init", "-q") + monkeypatch.setenv("GIT_DIR", str(other / ".git")) + monkeypatch.setenv("GIT_WORK_TREE", str(other)) + baseline = load_baseline(set_dir, "HEAD") + assert baseline.commit == sha + + +def test_git_that_cannot_run_raises(repo: Path, monkeypatch: pytest.MonkeyPatch) -> None: + set_dir = write_set(repo, 1, "{}") + commit(repo, "one") + + def broken(*args: object, **kwargs: object) -> None: + raise PermissionError("not executable") + + monkeypatch.setattr(subprocess, "run", broken) + with pytest.raises(BaselineError, match="cannot run git"): + load_baseline(set_dir, "HEAD")