"""구현 해시 — 모듈의 AST import 폐포 × 파일 바이트 (계획 2026-09-24-phase1a D7). 세 갈래가 같은 재료를 쓴다: - **스텝**(`step_impl_hashes`): 스텝 클래스 모듈에서 시작한 import 폐포. - **평가기**(`evaluator_impl_hash`): 평가기 클래스(합성이면 하위 전부)의 모듈에서 시작한 폐포. - **런타임**(`runtime_impl_hash`): `RUNTIME_MODULES` + 실제로 쓴 프로바이더 모듈 — 폐포를 돌지 않고 목록의 파일 바이트만 본다(목록이 곧 정의). 모듈 → 파일은 **이름으로** 푼다(`ImplRoots`). 이미 import 된 모듈의 `__file__` 이나 importlib spec 을 쓰지 않으므로, 테스트가 기본 루트를 tmp 사본으로 바꿔 끼우면 재import 없이 "구현만 바꾼" 상황이 만들어진다. 해시는 계산하는 순간 디스크의 파일을 읽는다. """ from __future__ import annotations import ast import os import sys import sysconfig from collections.abc import Iterable, Sequence from dataclasses import dataclass, field from pathlib import Path from typing import Any from poc_bundle.canonical import content_sha256, json_fingerprint import solar_eval #: 엔진 패키지 이름 — 패키지 루트에서는 이 이름 아래 모듈만 푼다(서드파티 차단). ENGINE_PACKAGE = "solar_eval" #: 러너·파이프라인 실행기·프롬프트 조립 — 모든 스텝에 똑같이 영향을 주는 프레임워크 모듈. #: 여기에 이번 run 이 쓰는 프로바이더 모듈을 더해 `runtime_impl_hash` 를 뜬다. 테스트가 집합을 고정한다. #: 러너에서 떼어 낸 도우미(입력·정답 추출 `run_records`, 행 선택 `dataset_prep`·`row_filter`, 파이프라인 #: 생성 `pipeline_factory`)도 러너 로직이라 함께 본다 — `solar_eval.core.*` 는 스텝·평가기 폐포에서 빠지므로 #: 여기 없으면 어떤 해시도 이 파일들을 보지 않는다. 테스트가 러너의 core import 가 전부 여기 있는지 지킨다. RUNTIME_MODULES: tuple[str, ...] = ( "solar_eval.core.runner", "solar_eval.core.dataset_loader", "solar_eval.core.dataset_prep", "solar_eval.core.row_filter", "solar_eval.core.pipeline_factory", "solar_eval.core.run_records", "solar_eval.pipelines.pipeline", "solar_eval.pipelines.registry", "solar_eval.pipelines.base", "solar_eval.evaluators.base", "solar_eval.evaluators.registry", "solar_eval.providers.base", "solar_eval.models.prompt_version", "solar_eval.models.sample", ) #: 스텝·평가기 폐포에서 빼는 공용 기반 — 런타임 해시가 한 번 보거나 출력과 무관한 것. _EXCLUDED_EXACT = frozenset( {*RUNTIME_MODULES, "solar_eval.pipelines.errors", "solar_eval.config", "solar_eval._version"} ) _EXCLUDED_PREFIXES = ( "solar_eval.providers.", "solar_eval.cli.", "solar_eval.stores.", "solar_eval.core.", ) #: 구현 해시 라벨 접두어 — `pkg:<루트 기준 POSIX 경로>`. LABEL_PREFIX = "pkg:" #: 루트에서 풀 수 없는 프로바이더 모듈(테스트 mock 등)의 라벨 접두어. 값은 null 로 들어간다. UNRESOLVED_PREFIX = "unresolved:" class ImplRootError(ValueError): """구현 해시 루트로 쓸 수 없는 디렉토리(서드파티·표준 라이브러리 영역).""" def _forbidden_bases() -> list[Path]: """등록 루트로 거부하는 영역 — site-packages·표준 라이브러리·인터프리터 prefix.""" paths = sysconfig.get_paths() bases = [paths.get(k) for k in ("purelib", "platlib", "stdlib")] bases += [sys.prefix, sys.base_prefix] return [Path(b).resolve() for b in bases if b] def _is_within(path: Path, base: Path) -> bool: try: path.relative_to(base) except ValueError: return False return True @dataclass(frozen=True) class ResolvedModule: """이름으로 푼 모듈 하나. `label` 은 지문 키(`pkg:solar_eval/pipelines/rules.py`).""" name: str path: Path label: str @dataclass(frozen=True) class ImplRoots: """모듈 이름 → 파일 해석 루트. - `package_parent`: `solar_eval` 패키지의 부모 디렉토리. 여기서는 `solar_eval.*` 이름만 푼다 — 엔진이 site-packages 에 설치돼 있어도 서드파티가 폐포에 들어오지 않는다. - `extra`: 테스트·확장이 명시 등록한 디렉토리. 여기서는 어떤 이름이든 푼다. 서드파티·표준 라이브러리 영역(`sysconfig` purelib/platlib/stdlib, `sys.prefix`, `sys.base_prefix`)은 거부한다 (uv 워크스페이스 venv 가 레포 안에 있어 "레포 안" 규칙이면 httpx 가 폐포에 들어온다 — 검토 F3). """ package_parent: Path extra: tuple[Path, ...] = field(default=()) def __post_init__(self) -> None: forbidden = _forbidden_bases() for root in self.extra: resolved = Path(root).resolve() if any(_is_within(resolved, base) for base in forbidden): raise ImplRootError( f"{root} is inside the interpreter/site-packages area — third-party code is " "covered by dependency_lock, not by implementation hashes" ) @classmethod def for_engine(cls, extra: Iterable[Path] = ()) -> ImplRoots: """지금 import 된 `solar_eval` 패키지의 부모 + 등록 디렉토리.""" parent = Path(solar_eval.__file__).resolve().parent.parent return cls(parent, tuple(Path(p) for p in extra)) def with_extra(self, *dirs: Path) -> ImplRoots: return ImplRoots(self.package_parent, (*self.extra, *(Path(d) for d in dirs))) def resolve(self, name: str) -> ResolvedModule | None: """모듈 이름을 파일로 푼다: `R//.py` 또는 `R///__init__.py`. 없으면 None.""" parts = name.split(".") if not all(p.isidentifier() for p in parts): return None roots: list[Path] = [] if parts[0] == ENGINE_PACKAGE: roots.append(self.package_parent) roots.extend(self.extra) for root in roots: base = Path(root).joinpath(*parts) for candidate in (base.with_suffix(".py"), base / "__init__.py"): if candidate.is_file() and _exact_case(Path(root), candidate): rel = candidate.relative_to(root).as_posix() return ResolvedModule(name, candidate, LABEL_PREFIX + rel) return None def _exact_case(root: Path, candidate: Path) -> bool: """`candidate` 의 경로 성분이 디렉토리 목록의 이름과 **대소문자까지** 같은가. macOS APFS 의 `is_file()` 은 대소문자를 무시한다 — `from pkg import Helper`(클래스)가 형제 모듈 `pkg/helper.py` 로 잘못 풀려, 같은 코드가 Linux 와 다른 폐포·라벨을 낸다. 파이썬 import 는 대소문자를 구분하므로 여기서도 목록과 정확히 대조해 Linux 와 같게 한다. """ current = root for part in candidate.relative_to(root).parts: try: names = os.listdir(current) except OSError: return False if part not in names: return False current = current / part return True # 기본 루트 — None 이면 `ImplRoots.for_engine()`. 테스트는 `set_default_roots` 로 사본을 끼운다. _DEFAULT_ROOTS: ImplRoots | None = None def default_roots() -> ImplRoots: """기본 해석 루트. `set_default_roots` 로 바꾼 값이 있으면 그것.""" return _DEFAULT_ROOTS if _DEFAULT_ROOTS is not None else ImplRoots.for_engine() def set_default_roots(roots: ImplRoots | None) -> ImplRoots | None: """기본 루트를 바꾸고 이전 값을 돌려준다(복원용). None 이면 엔진 기본으로 되돌린다.""" global _DEFAULT_ROOTS previous = _DEFAULT_ROOTS _DEFAULT_ROOTS = roots return previous def is_excluded(module: ResolvedModule) -> bool: """스텝·평가기 폐포에서 빼는가 — 런타임 목록·공용 기반·모든 패키지 `__init__`.""" if module.path.name == "__init__.py": return True if module.name in _EXCLUDED_EXACT: return True return module.name.startswith(_EXCLUDED_PREFIXES) def _package_of(module: ResolvedModule) -> str: if module.path.name == "__init__.py": return module.name return module.name.rpartition(".")[0] def _absolute_from(module: ResolvedModule, node: ast.ImportFrom) -> str | None: """`from ..x import y` 의 기준 모듈 이름. 최상위 밖으로 나가면 None.""" if node.level == 0: return node.module package = _package_of(module).split(".") if _package_of(module) else [] keep = len(package) - (node.level - 1) if keep < 0 or (keep == 0 and not node.module): return None base = package[:keep] if node.module: base += node.module.split(".") return ".".join(base) if base else None def imported_names(module: ResolvedModule, roots: ImplRoots) -> list[str]: """모듈 소스의 **모든** import(함수 안·TYPE_CHECKING 블록 포함)가 가리키는 모듈 이름. `from P import X` 는 `P.X` 가 모듈이면 그 모듈, 아니면 `P`. """ tree = ast.parse(module.path.read_bytes(), filename=str(module.path)) names: list[str] = [] for node in ast.walk(tree): if isinstance(node, ast.Import): names.extend(alias.name for alias in node.names) elif isinstance(node, ast.ImportFrom): base = _absolute_from(module, node) if base is None: continue for alias in node.names: candidate = f"{base}.{alias.name}" is_module = alias.name != "*" and roots.resolve(candidate) is not None names.append(candidate if is_module else base) return names def import_closure( start: Iterable[str], roots: ImplRoots, *, exclude: bool = True ) -> dict[str, ResolvedModule]: """시작 모듈들에서 루트 안으로 닿는 import 폐포. 시작 모듈은 제외 규칙과 무관하게 들어간다. Raises: ValueError: 시작 모듈을 루트에서 풀 수 없을 때(구현을 볼 수 없는 스텝·평가기). """ closure: dict[str, ResolvedModule] = {} queue: list[ResolvedModule] = [] for name in start: resolved = roots.resolve(name) if resolved is None: raise ValueError( f"module {name!r} is not under the implementation roots " f"({roots.package_parent}, extra={list(roots.extra)}) — register its directory" ) queue.append(resolved) while queue: module = queue.pop() if module.name in closure: continue closure[module.name] = module for name in imported_names(module, roots): found = roots.resolve(name) if found is None or found.name in closure: continue if exclude and is_excluded(found): continue queue.append(found) return closure def impl_hash(modules: Iterable[ResolvedModule]) -> str: """`json_fingerprint({label: content_sha256(파일 바이트)})` — 주석 변경도 해시를 바꾼다(의도).""" return json_fingerprint({m.label: content_sha256(m.path) for m in modules}) def closure_hash(start: Iterable[str], roots: ImplRoots) -> tuple[str, list[str]]: """(폐포 해시, 정렬된 라벨 목록).""" closure = import_closure(start, roots) return impl_hash(closure.values()), sorted(m.label for m in closure.values()) def step_impl_hashes( pipeline: Any, roots: ImplRoots | None = None ) -> tuple[dict[str, str], dict[str, list[str]]]: """생성된 `Pipeline` 의 스텝마다 (키 → 해시, 키 → 폐포 라벨). 키는 레지스트리 조회 이름. single_step 의 암묵 `llm_completion` 도 파이프라인 객체에 있으므로 들어간다(검토 F10). """ from solar_eval.pipelines.registry import step_key roots = roots or default_roots() hashes: dict[str, str] = {} modules: dict[str, list[str]] = {} for step in pipeline.steps: key = step_key(step.config) if key in hashes: continue hashes[key], modules[key] = closure_hash([type(step).__module__], roots) return dict(sorted(hashes.items())), dict(sorted(modules.items())) def _evaluator_modules(evaluator: Any) -> list[str]: names = [type(evaluator).__module__] for child in evaluator.sub_evaluators(): names.extend(_evaluator_modules(child)) return names def evaluator_impl_hash(evaluator: Any, roots: ImplRoots | None = None) -> tuple[str, list[str]]: """평가기(합성이면 하위 전부) 모듈에서 시작한 폐포의 (해시, 라벨).""" return closure_hash(_evaluator_modules(evaluator), roots or default_roots()) def provider_module(provider: Any) -> str: """프로바이더(인스턴스나 클래스)가 정의된 모듈 이름.""" return provider.__module__ if isinstance(provider, type) else type(provider).__module__ def runtime_impl_hash( providers: Sequence[Any], roots: ImplRoots | None = None ) -> tuple[str, list[str]]: """`RUNTIME_MODULES` + 프로바이더 모듈의 파일 바이트 지문 (폐포 없음). 프로바이더는 인스턴스나 클래스를 받는다. 루트에서 풀 수 없는 프로바이더 모듈(테스트 mock 등)은 `unresolved:<모듈>` 키에 null 로 들어간다 — 모르는 코드를 조용히 빼지 않는다. Raises: ValueError: `RUNTIME_MODULES` 중 하나를 루트에서 풀 수 없을 때. """ return runtime_impl_hash_for_modules([provider_module(p) for p in providers], roots) def runtime_impl_hash_for_modules( provider_modules: Iterable[str], roots: ImplRoots | None = None ) -> tuple[str, list[str]]: """`runtime_impl_hash` 의 모듈 이름판 — 재채점(`with_evaluator`)이 기록된 모듈 이름으로 다시 뜬다.""" roots = roots or default_roots() entries: dict[str, str | None] = {} for name in RUNTIME_MODULES: resolved = roots.resolve(name) if resolved is None: raise ValueError(f"runtime module {name!r} not found under {roots.package_parent}") entries[resolved.label] = content_sha256(resolved.path) for name in sorted(set(provider_modules)): resolved = roots.resolve(name) if resolved is None: entries[UNRESOLVED_PREFIX + name] = None else: entries[resolved.label] = content_sha256(resolved.path) return json_fingerprint(entries), sorted(entries) def engine_tree_sha256(roots: ImplRoots | None = None) -> str: """엔진 패키지 트리(`solar_eval/**/*.py`, `__pycache__` 제외)의 파일 바이트 지문 — provenance 용. git 없이도 계산된다. 키는 패키지 부모 기준 POSIX 경로(`solar_eval/core/runner.py`). """ parent = (roots or default_roots()).package_parent package = Path(parent) / ENGINE_PACKAGE entries = { path.relative_to(parent).as_posix(): content_sha256(path) for path in sorted(package.rglob("*.py")) if "__pycache__" not in path.relative_to(parent).parts } return json_fingerprint(entries)