Add load_baseline reading an eval set from a git ref
Archive the set folder at the commit, unpack into a temp dir and read cases and recorded responses into memory; the working tree stays untouched. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e9c5913025
commit
8f3844d650
3 files changed
+276
No files matched your search
@@ -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
|
||||
Reference in new issue
Block a user