"""추론 실패 샘플의 지문 — run.json `failed_sample_keys` (LP5 D-LP5-4 · 계획 §2.4). 러너는 실패 위치(`failed_sample_indices`)와 예외 타입(`failed_sample_errors`)만 run.json 에 쓴다 — 러너 경로는 `poc_bundle` 을 import 하지 않는다(D18). 이 모듈은 CLI 층이라 `poc_bundle.keys` 로 지문을 뜰 수 있다: `execute_plan` 이 러너가 **정상 반환한 뒤** 실패 위치마다 준비된 데이터셋의 원본 행에 결과 행과 같은 `extract_input` · `extract_golden` 을 적용해 `{sample_idx, input_key, golden_key, error_type}` 를 더한다. 텍스트는 싣지 않는다 — hex 지문과 타입 이름뿐이다. 계산할 수 없으면(위치가 선택 밖 · 입력이 빈 객체 · JCS 가 거부하는 값) **아무것도 쓰지 않는다**(= 모름). wrap 은 그때 `failures.jsonl` 을 생략한다. 단 재개 전 시도가 남긴 목록이 run 문서에 있으면 `[]` 로 덮는다(`record_failure_keys` — 낡은 지문을 남기지 않는다). 경고 한 줄에는 이유만 적고 값은 적지 않는다. """ from __future__ import annotations import asyncio import inspect import json from collections.abc import Mapping from typing import Any import click from poc_bundle.keys import golden_key, input_key from poc_bundle.v11 import FAILED_SAMPLE_KEYS_KEY from solar_eval.core.run_records import FAILED_SAMPLE_ERRORS_KEY, extract_golden, extract_input #: `failed_sample_errors` 에 그 위치가 없을 때의 타입 이름(wrap 은 `exception:unknown` 으로 적는다). UNKNOWN_ERROR_TYPE = "unknown" class _KeysUnknown(Exception): """지문을 뜰 수 없다 — 이유 한 마디만 싣는다(값은 싣지 않는다).""" def failure_keys( run_doc: Mapping[str, Any] | None, prepared: Any, task_config: Mapping[str, Any] ) -> list[dict[str, Any]] | None: """run 문서의 실패 위치 → `failed_sample_keys` 원소들(sample_idx 순). 모르면 None. `prepared` 는 `PreparedDataset`(또는 `selected` 가 `(원본 위치, 행)` 목록인 객체)이다. 실패가 없으면 `[]` 이다. """ try: indices = _failed_indices(run_doc) rows = dict(prepared.selected) types = _error_types(run_doc.get(FAILED_SAMPLE_ERRORS_KEY)) return [_entry(idx, rows, task_config, types) for idx in sorted(indices)] except _KeysUnknown as unknown: click.secho(f" failure keys not recorded ({unknown})", fg="yellow", err=True) return None def record_failure_keys( store: Any, run_id: str, prepared: Any, task_config: Mapping[str, Any] ) -> None: """run 문서를 읽어 실패 지문을 계산하고 `update_run` 으로 더한다. run 문서에 앞선 시도(재개 전)가 남긴 비지 않은 목록이 있으면 **늘 덮는다** — 저장소 `update_run` 은 병합이라 덮지 않으면 낡은 목록이 남는다. 새 목록이 있으면 그것으로, 실패가 없으면(`[]`, 재개가 실패를 모두 회복) `[]` 로 (wrap 이 0행을 쓴다), 모르면(None) 역시 `[]` 로 덮는다 — `[]` 는 비지 않은 `failed_sample_indices` 와 집합이 달라 wrap 이 생략(모름)하므로, 낡은 지문이 우연히 같은 위치 집합과 맞아 틀린 쌍으로 쓰이는 길이 없다. 낡은 목록이 없으면: 모르면 쓰지 않고, 실패가 없어도 쓰지 않는다 — 실패 없음은 `failed_sample_indices = []` 가 이미 말한다(성공 run 마다 run.json 을 한 번 더 쓰지 않는다). run 문서를 읽을 수 없는 저장소(`load_run_meta` 없음)는 모름이다. """ loader = getattr(store, "load_run_meta", None) run_doc = loader() if callable(loader) else None keys = failure_keys(run_doc, prepared, task_config) if _has_stale_keys(run_doc): keys = keys or [] elif not keys: return pending = store.update_run(run_id, {FAILED_SAMPLE_KEYS_KEY: keys}) if inspect.isawaitable(pending): asyncio.run(pending) def _has_stale_keys(run_doc: Mapping[str, Any] | None) -> bool: """run 문서에 `[]` 가 아닌 `failed_sample_keys` 가 이미 있다(앞선 시도의 목록 — 모양은 따지지 않는다).""" return isinstance(run_doc, Mapping) and run_doc.get(FAILED_SAMPLE_KEYS_KEY, []) != [] def _failed_indices(run_doc: Mapping[str, Any] | None) -> list[int]: if not isinstance(run_doc, Mapping): raise _KeysUnknown("run document unreadable") indices = run_doc.get("failed_sample_indices") if not isinstance(indices, list): raise _KeysUnknown("no failed_sample_indices list") if not all(isinstance(i, int) and not isinstance(i, bool) and i >= 0 for i in indices): raise _KeysUnknown("failed_sample_indices is not a list of positions") if len(set(indices)) != len(indices): raise _KeysUnknown("failed_sample_indices has duplicates") return indices def _error_types(errors: Any) -> dict[int, str]: """`failed_sample_errors` → `{sample_idx: 타입 이름}`. 모양이 틀린 원소는 건너뛴다(→ unknown).""" if not isinstance(errors, list): return {} types: dict[int, str] = {} for element in errors: if not isinstance(element, Mapping): continue idx, name = element.get("sample_idx"), element.get("error_type") if isinstance(idx, int) and not isinstance(idx, bool) and isinstance(name, str) and name: types[idx] = name return types def _entry( idx: int, rows: Mapping[int, Any], task_config: Mapping[str, Any], types: Mapping[int, str] ) -> dict[str, Any]: sample = rows.get(idx) if not isinstance(sample, Mapping): raise _KeysUnknown("failed position outside the selection") input_data = _as_stored(extract_input(sample, task_config.get("input_fields", []))) if not input_data: raise _KeysUnknown("empty input") golden = _as_stored(extract_golden(sample, task_config)) try: # items 규칙과 같다 — 엔진 run 의 입력 정체성은 엔진이 고른 input 객체 전체(fields=None). ik, gk = input_key(input_data, None), golden_key(golden) except (TypeError, ValueError) as exc: # CanonicalizationError 는 ValueError 다 raise _KeysUnknown(f"input not fingerprintable: {type(exc).__name__}") from None return { "sample_idx": idx, "input_key": ik, "golden_key": gk, "error_type": types.get(idx, UNKNOWN_ERROR_TYPE), } def _as_stored(value: Any) -> Any: """결과 저장소(`JsonlStore.insert_run_result`)가 쓰는 직렬화를 한 번 거친 값. items 는 results.jsonl 을 다시 읽어 지문을 뜨므로, 같은 원본 행이면 같은 키가 나오게 같은 `json.dumps` 왕복을 거친다(튜플 → 목록 · 문자열이 아닌 키 → 문자열). 직렬화할 수 없으면 모름. """ try: return json.loads(json.dumps(value, ensure_ascii=False)) except (TypeError, ValueError) as exc: raise _KeysUnknown(f"input not serializable: {type(exc).__name__}") from None