"""case 전체 재채점 — `solar-eval score proofread-diff --case a/c --all` (계획 2026-09-26 L3b §3.2·D6). 미러의 `accounts///eval/bundles` 에서 run_id 별 최신 커밋 번들을 `poc_bundle.adopt` 로 고르고(최신이 invalid 면 이전으로 넘어가지 않고 `latest_bundle_invalid` skip), 채택된 번들마다 `rescore_run_bundle` 을 부른다. - `bundles` 영역 디렉토리가 없으면 case 오류 `case_area_missing`(해석한 경로를 싣는다) — case 오타나 `--mirror-root` 층 어긋남(§2.1 "미러 루트 층")이 "할 일 없음·종료 0" 으로 숨지 않게. - 영역은 있는데 커밋된 run 번들이 0 이면 case 오류 `case_area_empty`(해석한 경로) — 같은 이유다(계획 2026-09-27 L6 §2.11, L3b 후속 3). run 필터가 있어도 이 판정이 먼저다. - 영역에 매니페스트를 못 읽는 번들이 하나라도 있으면(`AdoptError`) case 전체가 오류다 — 어느 run 의 번들인지 모르는 채로 채택하지 않는다(fail closed). run 필터가 있어도 영역 전체를 읽는다 — 필터가 fail closed 를 약하게 만들지 않게. - **run 필터**(`run_ids`, L6 §2.11 — 엔진 종료 훅이 run 하나만 재채점한다): 채택 목록(run_id 별 커밋 번들)을 거른다. 채택 규칙은 필터 없는 case 모드와 같다. 요청한 run 이 영역에 없으면 run 마다 오류 `run_not_in_mirror`. 값 규칙 (`is_valid_run_id` — 공백만이 아님·제어 문자 없음·512자 이하)은 CLI `--run` 과 이 함수 경계가 함께 쓴다. - run 하나의 오류(`RescoreError`)는 그 run 만 오류로 세고 다음 run 을 계속한다 — 종료 코드는 CLI 가 `errors` 로 정한다. - 평가기 문서는 case 한 번에 한 번 뜬다(모든 run 이 같은 `evaluator_config_hash` 를 쓴다). """ from __future__ import annotations import re from collections import Counter from collections.abc import Collection, Mapping, Sequence from dataclasses import dataclass, field from datetime import datetime from pathlib import Path from typing import Any from poc_bundle.adopt import AdoptError, Committed, adopt_run_bundle, committed_run_bundles from solar_eval.rescore.evaluator_doc import current_evaluator_document from solar_eval.rescore.from_bundle import ( ERR_ADOPT, SKIP_LATEST_INVALID, RescoreError, RescoreOutcome, rescore_run_bundle, ) from solar_eval.rescore.paths import BUNDLES_AREA, mirror_area_dir, resolve_mirror_root #: case 오류 — 미러 `bundles` 영역이 없다(case 오타·`--mirror-root` 층 어긋남). 아무것도 안 한 채 성공하지 않게. ERR_CASE_AREA_MISSING = "case_area_missing" #: case 오류 — `bundles` 영역은 있는데 커밋된 run 번들이 0 이다(L6 §2.11). ERR_CASE_AREA_EMPTY = "case_area_empty" #: run 오류 — run 필터로 요청한 run 의 커밋 번들이 미러 영역에 없다(L6 §2.11). ERR_RUN_NOT_IN_MIRROR = "run_not_in_mirror" #: run 필터 값 하나의 글자 수 상한(코드 포인트) — ES `hub ingest --expect-run` 과 같다(L6 §2.9). MAX_RUN_ID_LENGTH = 512 # C0·DEL·C1 제어 문자 — ES `--expect-run` 과 같은 범위. stderr `error …` 줄을 위조하지 못하게 한다 _CONTROL_CHARACTER = re.compile(r"[\x00-\x1f\x7f-\x9f]") def is_valid_run_id(value: object) -> bool: """run 필터 값 하나 — 공백만이 아닌 문자열, 제어 문자 없음, `MAX_RUN_ID_LENGTH` 자 이하(CLI `--run` 과 같은 규칙).""" return ( isinstance(value, str) and bool(value.strip()) and len(value) <= MAX_RUN_ID_LENGTH and _CONTROL_CHARACTER.search(value) is None ) @dataclass(frozen=True) class RunFailure: """run 하나(또는 case 전체, `run_id=None`)의 오류 — id·코드와, 있으면 경로만(메시지 원문은 싣지 않는다).""" run_id: str | None code: str detail: str | None = None @dataclass class CaseSummary: """case 재채점 결과 — run 결과 목록과 오류.""" outcomes: list[RescoreOutcome] = field(default_factory=list) failures: list[RunFailure] = field(default_factory=list) def to_json(self) -> dict[str, Any]: """§2.1 요약 줄 `{written, exists, skipped:{code:n}, errors, n_original_missing}`.""" statuses = Counter(o.status for o in self.outcomes) skipped = Counter(o.code for o in self.outcomes if o.status == "skip") return { "written": statuses.get("written", 0), "exists": statuses.get("exists", 0), "skipped": dict(sorted(skipped.items())), "errors": len(self.failures), "n_original_missing": sum(o.n_original_missing for o in self.outcomes), } def rescore_case( account: str, case: str, *, mirror_root: Path | None = None, out_dir: Path | None = None, now: datetime | None = None, repo_root: Path | None = None, run_ids: Collection[str] | None = None, ) -> CaseSummary: """미러의 한 case 를 재채점한다. `out_dir` 가 None 이면 미러 `evaluations` 에 놓는다(`mirror_bundle`). `mirror_root` 는 미러 버킷의 부모(기본 데이터 홈 `blob-mirror`) — 입력 run 번들도 여기서 읽는다. `run_ids` 를 주면 그 run 들만 재채점한다(없는 run 은 `run_not_in_mirror`). 문자열 하나(`TypeError`)나 빈 모음· `is_valid_run_id` 를 못 넘는 원소(`ValueError`)는 호출자 버그라 즉시 거부한다 — 글자 단위 필터나 "할 일 없음·성공", stderr 줄 위조가 되지 않게. """ wanted = _checked_run_ids(run_ids) summary = CaseSummary() by_run = _committed_by_run(mirror_root, account, case, summary) if by_run is None: return summary selected = sorted(by_run) if wanted is None else sorted(wanted & by_run.keys()) if wanted is not None: missing = sorted(wanted - by_run.keys()) summary.failures.extend(RunFailure(r, ERR_RUN_NOT_IN_MIRROR) for r in missing) evaluator = current_evaluator_document() root = resolve_mirror_root(mirror_root) for run_id in selected: _rescore_one(run_id, by_run[run_id], summary, out_dir, root, now, evaluator, repo_root) return summary def _checked_run_ids(run_ids: Collection[str] | None) -> frozenset[str] | None: """run 필터 경계 검사 — None(필터 없음) 또는 `is_valid_run_id` 를 넘는 값의 비어 있지 않은 모음.""" if run_ids is None: return None if isinstance(run_ids, str | bytes): raise TypeError("run_ids must be a collection of run ids, not a single string") wanted = frozenset(run_ids) if not wanted: raise ValueError("run_ids must not be empty (pass None for every run)") if not all(is_valid_run_id(r) for r in wanted): raise ValueError( "run_ids must be non-blank strings without control characters," f" at most {MAX_RUN_ID_LENGTH} characters" ) return wanted def _committed_by_run( mirror_root: Path | None, account: str, case: str, summary: CaseSummary ) -> Mapping[str, Sequence[Committed]] | None: """영역의 커밋 run 번들(run_id 별). case 오류면 `summary` 에 싣고 None.""" bundles_dir = mirror_area_dir(mirror_root, account, case, BUNDLES_AREA) if not bundles_dir.is_dir(): # `committed_run_bundles` 는 없는 영역을 빈 dict 로 본다 — 그대로 두면 요약이 전부 0 인 채 종료 0 이다 summary.failures.append(RunFailure(None, ERR_CASE_AREA_MISSING, str(bundles_dir))) return None try: by_run = committed_run_bundles(bundles_dir) except AdoptError: summary.failures.append(RunFailure(None, ERR_ADOPT)) return None if not by_run: # 있는데 비었다 — 백필 전이거나 영역 경로가 어긋났다. 할 일 없음·종료 0 으로 숨기지 않는다 summary.failures.append(RunFailure(None, ERR_CASE_AREA_EMPTY, str(bundles_dir))) return None return by_run def _rescore_one( run_id: str, cands: Sequence[Committed], summary: CaseSummary, out_dir: Path | None, root: Path, now: datetime | None, evaluator: Mapping[str, Any], repo_root: Path | None, ) -> None: """run 하나 — 최신 번들 채택(invalid 면 skip) 뒤 재채점. 결과·오류를 `summary` 에 싣는다.""" adoption = adopt_run_bundle(cands) if adoption.status != "ok": summary.outcomes.append(RescoreOutcome("skip", run_id, code=SKIP_LATEST_INVALID)) return try: outcome = rescore_run_bundle( adoption.committed.path, out_dir, mirror_root=None if out_dir is not None else root, now=now, evaluator=evaluator, repo_root=repo_root, ) except RescoreError as exc: summary.failures.append(RunFailure(exc.run_id or run_id, exc.code)) return summary.outcomes.append(outcome)