"""run 산출물 레코드 조립 -- results 행 · eval_details 행 · evaluation 문서. 러너(`execute_run`)와 `runs eval`(재채점) CLI 가 같은 모양을 쓰도록 한 곳에 둔다 (예전엔 두 곳에 복붙돼 있었다). 저장 키 이름은 eval-store 의 `resultRowSchema`· `evaluationJsonSchema` 와 하위 호환이어야 하므로 바꾸지 않는다. `evaluation` 문서의 `eval_model` 은 **인자**다 -- 어떤 judge 모델로 채점했는지는 호출자(평가기)가 안다. 이 모듈이 값을 지어내지 않는다. 이 모듈은 poc-bundle 패키지와 packaging 을 가져오지 않는다(D18). """ from __future__ import annotations from typing import Any, Mapping, Sequence from solar_eval.models.sample import EvalSample #: run.json 에서 추론 실패 샘플의 예외 타입 목록이 사는 키(LP5 D-LP5-4). 이름의 정본은 여기 한 곳이다 -- #: CLI 의 실패 지문 도우미(`cli/commands/failure_keys.py`)도 이 상수로 읽는다. FAILED_SAMPLE_ERRORS_KEY = "failed_sample_errors" def build_failure_errors(errors: Sequence[tuple[int, BaseException]]) -> list[dict[str, Any]]: """추론 실패 `(원본 sample_idx, 예외)` 목록 → run.json `failed_sample_errors` 원소들. 원소는 `{"sample_idx", "error_type"}` 두 키이고 `error_type` 은 예외 **타입 이름**뿐이다 -- 메시지는 입력 조각을 담을 수 있어 싣지 않는다. `sample_idx` 오름차순, 실패가 없으면 `[]`. """ ordered = sorted(errors, key=lambda pair: pair[0]) return [{"sample_idx": idx, "error_type": type(exc).__name__} for idx, exc in ordered] def extract_input(sample: Mapping[str, Any], input_fields: Sequence[str]) -> dict[str, Any]: """데이터 행에서 `input_fields` 만 골라 입력 dict 를 만든다(없는 키는 빈 문자열).""" return {field: sample.get(field, "") for field in input_fields} def extract_golden(sample: Mapping[str, Any], task_config: Mapping[str, Any]) -> Any: """데이터 행에서 정답(golden)을 꺼낸다 -- `golden_field` 우선, 다음 `golden_fields`.""" golden_field = task_config.get("golden_field") golden_fields = task_config.get("golden_fields") if golden_field: return sample.get(golden_field, "") if golden_fields: return {k: sample.get(v, "") for k, v in golden_fields.items()} return "" def build_eval_sample_from_result(result: dict[str, Any], reference: Any) -> EvalSample: """저장된 결과 dict(레거시 8+trace 키)에서 채점용 `EvalSample` 을 되살린다. `insert_run_result` 가 쓰는 키 이름(`golden`/`trace`)은 `EvalSample` 필드 이름 (`reference`/`artifacts`)과 다르다 -- eval-store 하위 호환을 위해 저장 스키마는 그대로 두고(마이그레이션 계획 §9-1) 채점 직전에만 여기서 되돌린다. `execute_run` 내부 루프와 `runs eval` CLI(재채점, 새 추론 없이 디스크의 `results.jsonl` 을 그대로 씀) 양쪽에서 공유한다. Args: result: `insert_run_result` 에 넘긴 것과 같은 형태(또는 `JsonlStore. load_existing_results()` 로 디스크에서 다시 읽은 것). `input`/`output`/ `trace` 키를 읽는다. reference: 정답(golden) 값. 호출자가 직접 넘긴다 -- 두 호출자의 golden 추출 경로가 다르기 때문이다(아래 참고). 이 함수는 어느 쪽인지 모른 채 값만 받아 그대로 `sample.reference` 에 채운다. - `execute_run` 내부 루프: `_golden_raw`(디스크에 안 남는 실행 중 임시 키, resume 시에도 매 샘플마다 새로 계산됨)를 넘긴다. - `runs eval` CLI: 디스크에 저장된 `golden` 키를 그대로 넘긴다 (`_golden_raw` 는 애초에 저장되지 않아 CLI 쪽엔 없다). Returns: `input`/`output`/`reference`/`artifacts` 가 채워진 `EvalSample`. `contexts` 는 아직 아무도 안 써서 기본값(`None`) 그대로다. """ trace = result.get("trace") or {} return EvalSample( input=result.get("input"), output=result.get("output"), reference=reference, artifacts=trace, ) def _usage_mapping(usage: Any) -> Mapping[str, Any]: """artifacts 의 `usage` 를 읽을 수 있는 dict 로 -- dict 가 아니면(없음·`None` 포함) 빈 dict. 빈 dict 에서 꺼낸 토큰 칸은 `None` 이 된다(측정 없음). 예전에는 `usage: None` 인 샘플이 `None.get` 으로 행 조립 자체를 죽였다. """ return usage if isinstance(usage, Mapping) else {} def build_result_row( run_id: str, sample_idx: int, input_data: dict[str, Any], golden: Any, eval_sample: EvalSample, meta: dict[str, Any] | None = None, ) -> dict[str, Any]: """results.jsonl 한 행. 오늘의 8키 + `trace`, 그리고 `meta_fields` 가 있을 때만 `meta`. `sample_idx` 는 **원본 파일의 0-based 레코드 위치**다(필터·limit 뒤에도, D2). trace 는 artifacts 전체를 그대로 넣는다 -- step_outputs 뿐 아니라 v24 가 채우는 judge_decisions/judge_tool_calls/self_consistency_runs/corrections 도 여기 안 넣으면 저장 직전에 통째로 버려진다 (실제 judge LLM 호출·self-consistency 반복 호출 비용이 나간 산출물이다). 특정 키만 하드코딩해 옮기면 다음에 파이프라인이 새 artifacts 키를 추가할 때마다 여기를 또 고쳐야 하므로 통째로 넘긴다 -- resultRowSchema.trace 는 .passthrough() 라 여분 키를 그대로 받는다 (source-schemas.ts:223-228). `meta` 는 input 이 아니다 -- 데이터 행의 태그·출처 복사본이고(D13), `meta_fields` 선언이 없으면 키 자체를 쓰지 않아 다른 프로젝트의 results 바이트가 그대로다. 사용량·지연(`input_tokens`·`output_tokens`·`inference_time_ms`)은 artifacts 에 없으면 `None` 이다(L6b B1 · D-M2-24) -- `0` 을 지어 넣으면 "측정 없음" 이 "0 을 썼다" 는 측정값과 구분되지 않는다. 값이 있으면 그대로 옮긴다(`0` 도 그대로) -- 사용량이 있는 행의 바이트는 예전과 같다. """ usage = _usage_mapping(eval_sample.artifacts.get("usage")) row: dict[str, Any] = { "run_id": run_id, "sample_idx": sample_idx, "input": input_data, "output": eval_sample.output, "golden": golden, "input_tokens": usage.get("prompt_tokens"), "output_tokens": usage.get("completion_tokens"), "inference_time_ms": eval_sample.artifacts.get("inference_time_ms"), "trace": { "step_outputs": {}, **eval_sample.artifacts, }, } if meta is not None: row["meta"] = meta return row def build_evaluation_doc( run_id: str, aggregated: Mapping[str, Any], eval_results: Sequence[Mapping[str, Any]], eval_failures: Sequence[Mapping[str, Any]], eval_model: str | None, ) -> dict[str, Any]: """evaluation.json 문서. 채점에 성공한 샘플이 하나도 없으면 점수 자리를 비운다 -- aggregate() 는 빈 입력에 0.0 을 돌려주는데, 그건 "0점을 받았다"는 측정값이라 "측정 자체가 없었다"와 구분되지 않는다. judge 가 통째로 죽은 run 이 Experiment Hub 차트에서 품질 급락으로 보이면 안 된다. """ overall_score = aggregated.get("overall_score", 0.0) if eval_results else None return { "run_id": run_id, "scores": aggregated.get("scores", {}), "overall_score": overall_score, "eval_model": eval_model, "eval_success_count": len(eval_results), "eval_failed_count": len(eval_failures), "failed_sample_indices": [f["sample_idx"] for f in eval_failures], } def build_eval_detail_docs( evaluation_id: Any, eval_results: Sequence[Mapping[str, Any]], eval_failures: Sequence[Mapping[str, Any]], ) -> list[dict[str, Any]]: """eval_details.jsonl 행들 -- 성공/실패 둘 다 한 행씩 남긴다. results.jsonl 과 eval_details.jsonl 이 항상 같은 sample_idx 집합을 가리키게 해서 부분적으로만 채점된 run 에서 "이 샘플은 왜 안 보이지"를 없앤다. """ docs: list[dict[str, Any]] = [] for er in eval_results: docs.append( { "evaluation_id": evaluation_id, "sample_idx": er["sample_idx"], "category_scores": er.get("category_scores", {}), "error_counts": { k: v.get("error_count", 0) for k, v in er.get("details", {}).items() if isinstance(v, dict) }, "severity": er.get("severity", ""), "score": er.get("score", 0.0), } ) for f in eval_failures: docs.append( { "evaluation_id": evaluation_id, "sample_idx": f["sample_idx"], "category_scores": {}, "error_counts": {}, "severity": None, # 0.0 이 아니라 None -- 채점 실패를 최저 점수와 구분한다 (F1). "score": None, "error": f["error"], } ) return docs