"""실행 환경 재료 — 의존 버전·엔진 버전·엔진 레포 상태 (계획 2026-09-24-phase1a D8·D9). config 에 들어가는 것(지문 대상)은 출력 경로에 있는 **직접** 런타임 의존과 엔진 버전·파이썬 부버전뿐이다. 전이 설치 폐포·uv.lock·엔진 커밋·트리 해시·dirty 는 provenance(지문 밖)로 간다 — 무관한 워크스페이스 멤버의 변화가 설정 지문을 흔들지 않게. """ from __future__ import annotations import logging import subprocess import sys from collections.abc import Callable from importlib import metadata from pathlib import Path from typing import Any from packaging.requirements import InvalidRequirement, Requirement from packaging.utils import canonicalize_name from poc_bundle.canonical import content_sha256 import solar_eval from solar_eval._version import __version__ from solar_eval.core.snapshot.impl_hash import ImplRoots, engine_tree_sha256 logger = logging.getLogger(__name__) #: 엔진 배포 이름. ENGINE_DISTRIBUTION = "solar-eval" #: 모델 입출력에 닿지 않는 직접 의존 — CLI 표시·설정 로드·번들 도구. `dependency_lock` 에서 뺀다. #: 새 직접 의존을 추가하면 이 목록이나 출력 의존 중 하나로 분류하기 전까지 테스트가 깨진다(의도). NON_OUTPUT_DEPENDENCIES = frozenset( {"click", "tabulate", "rich", "pydantic-settings", "poc-bundle", "packaging"} ) DEPENDENCY_LOCK_SCHEME = "direct-runtime/v1" #: config_dir 안에서 출력에 영향을 주는 경로(dirty 범위). scripts/·insights/·README 는 뺀다(검토 F12·m3). CONFIG_DIRTY_ENTRIES = ( "project.yaml", "prompts", "pipelines", "resources", "dataset/datasets.lock.yaml", ) GitRun = Callable[..., Any] def _marker_env() -> dict[str, str]: return {"extra": ""} def direct_requirements(distribution: str = ENGINE_DISTRIBUTION) -> list[str]: """배포의 직접 `Requires-Dist` 중 현재 환경에서 켜지는 것(extra 없음)의 정규화 이름(정렬).""" names: set[str] = set() for raw in metadata.requires(distribution) or []: try: req = Requirement(raw) except InvalidRequirement as exc: raise ValueError(f"{distribution}: unparsable requirement {raw!r}: {exc}") from exc if req.marker is not None and not req.marker.evaluate(_marker_env()): continue names.add(canonicalize_name(req.name)) return sorted(names) def direct_runtime_dependencies() -> dict[str, str]: """`dependency_lock.packages` — 출력 경로에 있는 직접 의존의 설치 버전.""" return { name: metadata.version(name) for name in direct_requirements() if name not in NON_OUTPUT_DEPENDENCIES } def dependency_lock() -> dict[str, Any]: return { "scheme": DEPENDENCY_LOCK_SCHEME, "root": ENGINE_DISTRIBUTION, "packages": direct_runtime_dependencies(), } def installed_closure(distribution: str = ENGINE_DISTRIBUTION) -> dict[str, str | None]: """엔진에서 닿는 설치 폐포 `{이름: 버전}` — provenance 전용(환경 재구성·디버그). 켜진 요구인데 설치돼 있지 않으면 버전 None 으로 남긴다(숨기지 않는다). """ seen: dict[str, str | None] = {} queue: list[str] = [str(canonicalize_name(distribution))] while queue: name = queue.pop() if name in seen: continue try: seen[name] = metadata.version(name) except metadata.PackageNotFoundError: seen[name] = None continue queue.extend(n for n in direct_requirements(name) if n not in seen) return dict(sorted(seen.items())) def runner_version() -> dict[str, str]: """`{"package", "version", "python": "."}` — 패치 버전은 넣지 않는다.""" return { "package": ENGINE_DISTRIBUTION, "version": __version__, "python": f"{sys.version_info.major}.{sys.version_info.minor}", } def engine_src_dir() -> Path: """엔진 소스 루트(`packages/solar-eval-python/src`) — `solar_eval.__file__` 기준.""" return Path(solar_eval.__file__).resolve().parent.parent def engine_repo(start: Path | None = None) -> Path | None: """엔진 코드가 든 git 레포 — `start`(기본 엔진 소스)에서 위로 `.git` 을 찾는다. `cfg.repo_root` 를 쓰지 않는다: `--projects-dir` 면 None 이 된다(검토 F13). 워크트리의 `.git` 은 파일이라 존재만 본다. """ here = (start or engine_src_dir()).resolve() for candidate in (here, *here.parents): if (candidate / ".git").exists(): return candidate return None def dirty_scope( repo: Path, config_dir: Path | None, repo_managed: bool, src_dir: Path | None = None ) -> list[str]: """dirty 판정 범위(레포 상대 POSIX, 정렬). 레포 밖 경로는 넣지 않는다.""" src = (src_dir or engine_src_dir()).resolve() candidates = [src, src.parent / "pyproject.toml", repo / "uv.lock"] if repo_managed and config_dir is not None: candidates += [Path(config_dir).resolve() / entry for entry in CONFIG_DIRTY_ENTRIES] root = repo.resolve() scope = set() for path in candidates: try: scope.add(path.resolve().relative_to(root).as_posix()) except ValueError: logger.warning("dirty scope path outside the engine repo, skipped: %s", path) return sorted(scope) def _git(run: GitRun, repo: Path, *args: str) -> str | None: """git 한 번. 실패(git 없음·레포 아님·비정상 종료)는 None — 호출자가 null 로 기록한다.""" try: result = run(["git", "-C", str(repo), *args], capture_output=True, text=True, check=True) except (OSError, subprocess.CalledProcessError) as exc: logger.warning("git %s failed in %s: %s", " ".join(args[:2]), repo, exc) return None return result.stdout def engine_state( config_dir: Path | None, repo_managed: bool, *, repo: Path | None = None, src_dir: Path | None = None, roots: ImplRoots | None = None, run: GitRun = subprocess.run, ) -> dict[str, Any]: """`provenance.engine = {commit, tree_sha256, dirty, dirty_scope}` (D8). `repo` 를 안 주면 `engine_repo()`. 레포를 못 찾거나 git 이 실패하면 `commit`·`dirty` 는 null, `tree_sha256` 은 git 없이도 계산된다. """ repo = repo if repo is not None else engine_repo(src_dir) tree = engine_tree_sha256(roots) if repo is None: return {"commit": None, "tree_sha256": tree, "dirty": None, "dirty_scope": []} scope = dirty_scope(repo, config_dir, repo_managed, src_dir) head = _git(run, repo, "rev-parse", "HEAD") # 빈 범위로 status 를 부르면 레포 전체를 본다 — 범위가 없으면 판정하지 않는다(null). # `--literal-pathspecs`: config_dir 이름의 `[`·`*`·`?` 를 glob 으로 읽지 않게(범위 밖 변경이 dirty 로). status = ( _git( run, repo, "--literal-pathspecs", "status", "--porcelain", "--untracked-files=normal", "--", *scope, ) if scope else None ) return { "commit": head.strip() if head else None, "tree_sha256": tree, "dirty": None if status is None else bool(status.strip()), "dirty_scope": scope, } def uv_lock_sha256(repo: Path | None) -> str | None: """레포 `uv.lock` 의 sha256 — provenance 전용(모노레포 lock 은 무관한 멤버로도 바뀐다).""" if repo is None: return None lock = repo / "uv.lock" return content_sha256(lock) if lock.is_file() else None