"""`solar-eval score` — 오프라인 재채점 명령 그룹 (계획 2026-09-26 L3b §2.1). `score proofread-diff` 는 run 번들의 `results.jsonl` 을 레거시 `lcs_diff` 와 같은 함수로 다시 채점해 채점 번들 (`poc-scoring/v1`, `purpose=rescore_after_fix`)로 낸다. 두 모드: - `…` 모드: 번들이 `…/eval/bundles/` 에 있으면 기본 출력은 `…/eval/evaluations`, 아니면 `--out` 필수. `--mirror` 면 각 번들 매니페스트 `case` 의 미러 `evaluations` 에 놓는다. - `--case a/c --all` 모드: 미러의 그 case run 번들 전부(`poc_bundle.adopt` 로 채택). `--mirror` 또는 `--out` 이 필요하다. `--run `(반복)를 주면 그 run 들만(계획 2026-09-27 L6 §2.11 — 채택 규칙은 같고, 영역에 없는 run 은 오류 `run_not_in_mirror`). `--run` 은 이 모드에서만 받고, 빈 값·공백만·제어 문자·512자 초과는 사용 오류다(ES `hub ingest --expect-run` 과 같은 범위 — 없는 run 이 stderr 에 그대로 찍히므로 줄 위조를 막는다). - `--out DIR` 과 `--mirror` 는 함께 쓰지 않는다. `--mirror-root` 는 미러 **버킷의 부모**다(§2.1 "미러 루트 층"). 디렉토리 모드에서는 `--mirror` 와 함께만 받는다. 없는 run 번들 경로는 사용 오류(종료 2)다. stdout 은 run 마다 한 줄 `written ` · `exists ` · `skip ` 이고, case 모드는 마지막 줄에 JSON 요약 `{written, exists, skipped:{code:n}, errors, n_original_missing}` 을 낸다. 오류는 stderr 에 `error ` 한 줄씩 (case 전체 오류는 run_id 자리에 `-`, `case_area_missing`·`case_area_empty` 는 뒤에 해석한 영역 경로를 붙인다). 어느 쪽에도 입력·출력·정답 원문은 싣지 않는다. 종료 코드: 0 = 전부 written/exists/규칙 skip · 1 = 오류 1건 이상 · 2 = 사용 오류. import 경계(D1): 이 모듈은 click 만 모듈 최상위에서 import 한다. `solar_eval.rescore`(그리고 그것이 끌어오는 `poc_bundle`)는 **명령 함수 안에서** import 한다 — `solar-eval` CLI 를 띄우는 것만으로 재채점기·번들 writer 가 로딩되지 않게. """ from __future__ import annotations import json import sys from pathlib import Path from typing import Any import click _DIR = click.Path(file_okay=False, path_type=Path) # 입력 run 번들은 있어야 한다 — 경로 오타가 규칙 skip(`latest_bundle_invalid`)·종료 0 으로 끝나지 않게 click 이 종료 2 로 막는다. _EXISTING_DIR = click.Path(exists=True, file_okay=False, path_type=Path) EXIT_ERRORS = 1 EXIT_USAGE = 2 @click.group("score") def score_group() -> None: """Offline rescoring of run bundles (scoring bundles, poc-scoring/v1).""" @score_group.command("proofread-diff") @click.argument("run_bundle_dirs", nargs=-1, type=_EXISTING_DIR) @click.option("--case", "case_key", default=None, help="accounts// as a/c (with --all).") @click.option("--all", "all_runs", is_flag=True, default=False, help="Every adopted run bundle.") @click.option("--out", "out_dir", type=_DIR, default=None, help="Parent dir for scoring bundles.") @click.option("--mirror", is_flag=True, default=False, help="Write into the local mirror.") @click.option( "--mirror-root", type=_DIR, default=None, help="Parent of the mirror bucket (default: data home blob-mirror).", ) @click.option( "--run", "run_ids", multiple=True, help="Only this run_id (repeatable; with --case --all).", ) def proofread_diff( run_bundle_dirs: tuple[Path, ...], case_key: str | None, all_runs: bool, out_dir: Path | None, mirror: bool, mirror_root: Path | None, run_ids: tuple[str, ...], ) -> None: """Rescore run bundles with proofread_diff@2 (same scoring as legacy lcs_diff).""" _check_usage(run_bundle_dirs, case_key, all_runs, out_dir, mirror, mirror_root, run_ids) if case_key is not None: code = _run_case(case_key, out_dir, mirror_root, frozenset(run_ids) or None) else: code = _run_dirs(run_bundle_dirs, out_dir, mirror_root if mirror else None, mirror) sys.exit(code) def _usage(message: str) -> None: click.echo(f"usage error: {message}", err=True) sys.exit(EXIT_USAGE) def _check_usage( dirs: tuple[Path, ...], case_key: str | None, all_runs: bool, out_dir: Path | None, mirror: bool, mirror_root: Path | None, run_ids: tuple[str, ...] = (), ) -> None: """두 모드의 인자 조합 — 어긋나면 종료 2.""" if out_dir is not None and mirror: _usage("--out and --mirror are mutually exclusive") if case_key is not None or all_runs: if dirs: _usage("give run bundle directories or --case/--all, not both") if case_key is None or not all_runs: _usage("--case a/c needs --all (and --all needs --case)") if out_dir is None and not mirror: _usage("--case --all needs --mirror or --out DIR") elif not dirs: _usage("give run bundle directories, or --case a/c --all") elif mirror_root is not None and not mirror: # 디렉토리 모드에서 --mirror-root 는 --mirror 의 출력 자리일 뿐이다 — 조용히 버리지 않는다 _usage("--mirror-root needs --mirror when rescoring run bundle directories") if run_ids: _check_run_filter(case_key, run_ids) def _check_run_filter(case_key: str | None, run_ids: tuple[str, ...]) -> None: """`--run` 은 case 모드의 run 필터다(L6 §2.11) — 디렉토리 모드에서 조용히 버리지 않고, 값은 경계에서 거른다. case 모드의 `--case`/`--all` 짝은 `_check_usage` 가 먼저 막으므로 여기서 `case_key is None` 이면 디렉토리 모드다. 값 규칙은 라이브러리 경계(`rescore_case`)와 같은 `is_valid_run_id` 다. 거부 문구에 값 원문은 싣지 않는다. """ from solar_eval.rescore.case import MAX_RUN_ID_LENGTH, is_valid_run_id if case_key is None: _usage("--run needs --case a/c --all (not run bundle directories)") if not all(is_valid_run_id(r) for r in run_ids): _usage( "--run needs a non-blank run_id without control characters," f" at most {MAX_RUN_ID_LENGTH} characters" ) def _run_case( case_key: str, out_dir: Path | None, mirror_root: Path | None, run_ids: frozenset[str] | None = None, ) -> int: from solar_eval.rescore.case import rescore_case from solar_eval.rescore.paths import RescorePathError, parse_case_key try: account, case = parse_case_key(case_key) except RescorePathError as exc: _usage(str(exc)) summary = rescore_case(account, case, mirror_root=mirror_root, out_dir=out_dir, run_ids=run_ids) for outcome in summary.outcomes: _echo_outcome(outcome) for failure in summary.failures: suffix = f" {failure.detail}" if failure.detail else "" click.echo(f"error {failure.run_id or '-'} {failure.code}{suffix}", err=True) report: dict[str, Any] = summary.to_json() click.echo(json.dumps(report, ensure_ascii=False, sort_keys=False)) return EXIT_ERRORS if report["errors"] else 0 def _run_dirs( dirs: tuple[Path, ...], out_dir: Path | None, mirror_root: Path | None, mirror: bool ) -> int: from solar_eval.rescore.evaluator_doc import current_evaluator_document from solar_eval.rescore.from_bundle import RescoreError, rescore_run_bundle from solar_eval.rescore.paths import default_evaluations_dir, resolve_mirror_root targets = [(d, out_dir or (None if mirror else default_evaluations_dir(d))) for d in dirs] missing = [d for d, target in targets if target is None and not mirror] if missing: _usage(f"{missing[0]} is not under …/eval/bundles/ — give --out DIR") root = resolve_mirror_root(mirror_root) if mirror else None evaluator = current_evaluator_document() errors = 0 for bundle_dir, target in targets: try: outcome = rescore_run_bundle(bundle_dir, target, mirror_root=root, evaluator=evaluator) except RescoreError as exc: click.echo(f"error {exc.run_id or bundle_dir.name} {exc.code}", err=True) errors += 1 continue _echo_outcome(outcome, fallback=bundle_dir.name) return EXIT_ERRORS if errors else 0 def _echo_outcome(outcome: Any, fallback: str = "-") -> None: if outcome.status == "skip": click.echo(f"skip {outcome.run_id or fallback} {outcome.code}") else: click.echo(f"{outcome.status} {outcome.path}")