"""hub 다리 (계획 2026-09-27 L6 §2.6 · D-L6-4 · D-L6-5 · C-L6-1 · C-L6-3). - argv(`build_hub_argv`) = `["pnpm", "--silent", "--fail-if-no-match", "--filter", "@poc/eval-store", "hub", "ingest", "--case", a/c, *("--expect-run", r …), "--repo", resolve(target.repo_root), "--mirror", blob_mirror_root()/<버킷>, "--index", hub_index_root(), *(["--i-understand-local-data"] if confirm_local)]`. URL 은 argv 에 싣지 않는다 — 출처가 환경 변수면 부모 환경 그대로(`env=None`), 설정 파일 `hub.database_url` 이면 `child_env`(부모 환경 + `HUB_DATABASE_URL`)로 **자식 환경으로만** 간다(계획 2026-09-28 L10 §2.6). 적재 하나뿐이다 — 이 모듈은 다른 hub 하위 명령을 짓지 않는다(`proc` 허용 목록이 한 번 더 막는다). - 실행은 **`proc.run_pnpm`(모듈 속성으로)** 만 — `cwd=workspace_root()`(코드 체크아웃, C-L6-9), `timeout=HUB_INGEST_TIMEOUT_SECONDS`. `FileNotFoundError` → `pnpm_missing`, `TimeoutExpired` → `timeout`. - 해석(`judge_hub`, 순수 — §2.6 표): 0 → ok(stdout JSON `expect.ok`, `ingest_id`) · 1 → `hub_)">`(필터 불일치면 `filter_no_match`) · 2 → `case_blocked:`·`case_failed:` · 3 → `schema_mismatch`(재구성하지 않는다, C-M2-3) · 4 → `run_not_ok:`(요청 순서로 처음 ok 가 아닌 run) · 그 밖 → `hub_exit_` · JSON 이 깨졌거나 모양이 다르면 `hub_output_unreadable`. - detail 에는 **코드·id 만** 싣는다(`ingest_id`·run 별 상태). hub 출력 원문(stderr 문구·요약의 다른 키)은 옮기지 않는다 — URL 이나 입력 조각이 섞여 있을 수 있다(D-L6-4). 외부 출력에서 뽑은 토큰은 `_TOKEN`(실패 stage 는 `_STAGE`) 문법으로 검사한다. - 다리가 실패하면(시간 초과 포함) hub CLI stderr 의 마지막 `[hub]` 줄 몇 개를 **콘솔(stderr)에만** 옮긴다 — 비밀을 가리고 길이를 자른 뒤(`diagnostic_lines`). 코드만으로는 무엇이 잘못됐는지 알 수 없어서다(리뷰 지적 6). 상태 파일에는 싣지 않는다. 가림은 환경 변수 값에 더해 설정 출처 값(`secrets` — `optin.HubOptIn.secrets`)도 본다. - opt-in(`HUB_DATABASE_URL`·설정 `hub:` 절)·확인·번들 유무 게이트는 여기가 아니라 `hook.gated_hub_leg` 한 곳이다. `poc_bundle` 은 함수 안에서만 import 한다(D-L6-14). """ from __future__ import annotations import json import re import subprocess from collections.abc import Mapping, Sequence from pathlib import Path from typing import Any import click from solar_eval.hub_hook import console, proc, status, target from solar_eval.hub_hook.optin import CONFIRM_FLAG from solar_eval.hub_hook.types import ( CASE_BLOCKED_PREFIX, CASE_FAILED_PREFIX, EXPECT_MISSING, EXPECT_NO_USABLE_BUNDLE, EXPECT_OK, EXPECT_ORPHANED, FILTER_NO_MATCH, HUB_CASE_BLOCKED, HUB_CASE_FAILED, HUB_EXIT_CASE, HUB_EXIT_EXPECT, HUB_EXIT_OK, HUB_EXIT_PREFIX, HUB_EXIT_REFUSED, HUB_EXIT_SCHEMA, HUB_FAILED_PREFIX, HUB_INGEST_TIMEOUT_SECONDS, HUB_OUTPUT_UNREADABLE, HUB_PACKAGE_FILTER, NO_WORKSPACE, PNPM_MISSING, PNPM_NO_MATCH, RUN_NOT_OK_PREFIX, SCHEMA_MISMATCH, STATUS_FAILED, TIMEOUT, LegResult, Target, ) #: pnpm 전역 옵션 — 출력은 스크립트 것만, 필터 불일치는 종료 1(pnpm 10.30.1 사실, §2.6). PNPM_PREFIX = ("pnpm", "--silent", "--fail-if-no-match", "--filter", HUB_PACKAGE_FILTER) HUB_INGEST = ("hub", "ingest") #: hub CLI stderr 오류 줄 `[hub] 오류(): …` 의 코드. _HUB_ERROR_LINE = re.compile(r"^\[hub\] 오류\(([a-z][a-z0-9_]{0,63})\)", re.MULTILINE) #: 외부 출력에서 뽑아 코드에 싣는 토큰(case 차단 코드·ingest_id)의 문법. _TOKEN = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}") #: 실패 stage — ES `orchestrate.ts` 가 내는 단계 이름(`datasets`·`run-bundles`·`digest`·`case_lock`·`unknown`)과 #: preflight 실패의 `preflight:<단계>`(리뷰 지적 5). `:` 은 한 번만 받는다. _STAGE = re.compile(r"[a-z][a-z0-9_-]{0,63}(?::[a-z][a-z0-9_-]{0,63})?") #: 실패한 hub 다리에서 콘솔(stderr)에 옮기는 hub CLI stderr 꼬리 — 줄 수와 한 줄 길이 상한(리뷰 지적 6). HUB_DIAG_MAX_LINES = 5 HUB_DIAG_MAX_CHARS = 300 _HUB_LOG_PREFIX = "[hub]" #: `--expect-run` 값 — 옵션으로 오인되지 않게 `-` 로 시작하지 않고 제어 문자가 없다. _CONTROL = re.compile(r"[\x00-\x1f\x7f-\x9f]") EXPECT_STATES = frozenset({EXPECT_OK, EXPECT_MISSING, EXPECT_NO_USABLE_BUNDLE, EXPECT_ORPHANED}) class _Unreadable(ValueError): """hub 출력이 기대한 모양이 아니다 — `hub_output_unreadable` 로 바뀐다(원문은 싣지 않는다).""" # ── argv(순수) ─────────────────────────────────────────────────────────── def build_hub_argv( target: Target, run_ids: Sequence[str], *, confirm_local: bool, env: Mapping[str, str] | None = None, ) -> list[str]: """hub 적재 argv(순수 — 경로는 `poc_bundle.home` 해석값). run_id 가 비었거나 옵션 모양이면 `ValueError`.""" from poc_bundle.home import blob_mirror_root, hub_index_root from poc_bundle.mirror import DEFAULT_BUCKET expect: list[str] = [] for run_id in _checked_run_ids(run_ids): expect += ["--expect-run", run_id] return [ *PNPM_PREFIX, *HUB_INGEST, "--case", target.case_ref, *expect, "--repo", # 절대 경로로 — 상대면 자식(pnpm 스크립트 cwd = ES 패키지 디렉토리)이 다른 곳으로 푼다(D-L6-5, 리뷰 지적 2). str(Path(target.repo_root).expanduser().resolve()), "--mirror", str(blob_mirror_root(env) / DEFAULT_BUCKET), "--index", str(hub_index_root(env)), *([CONFIRM_FLAG] if confirm_local else []), ] def _checked_run_ids(run_ids: Sequence[str]) -> list[str]: ids = list(run_ids) if not ids: raise ValueError("hub leg needs at least one run_id") for run_id in ids: if not isinstance(run_id, str) or not run_id or run_id.startswith("-"): raise ValueError("hub leg run_id must be a non-empty string not starting with '-'") if _CONTROL.search(run_id): raise ValueError("hub leg run_id has a control character") return ids # ── 판정(순수, §2.6 표) ────────────────────────────────────────────────── def judge_hub(result: subprocess.CompletedProcess[str], run_ids: Sequence[str]) -> LegResult: """hub CLI 종료 코드·출력 → `LegResult`. 출력 원문은 싣지 않는다.""" code = result.returncode stdout, stderr = result.stdout or "", result.stderr or "" if code != HUB_EXIT_OK and PNPM_NO_MATCH in f"{stdout}\n{stderr}": return LegResult.failed(FILTER_NO_MATCH) try: if code == HUB_EXIT_OK: return _judge_ok(stdout, run_ids) if code == HUB_EXIT_REFUSED: return LegResult.failed(_refusal_code(stderr)) if code == HUB_EXIT_CASE: return _judge_case(stdout, run_ids) if code == HUB_EXIT_SCHEMA: return LegResult.failed(SCHEMA_MISMATCH) if code == HUB_EXIT_EXPECT: return _judge_expect_failed(stdout, run_ids) except _Unreadable: return LegResult.failed(HUB_OUTPUT_UNREADABLE) return LegResult.failed(f"{HUB_EXIT_PREFIX}{code}") def _judge_ok(stdout: str, run_ids: Sequence[str]) -> LegResult: doc = _summary(stdout) states = _expect_states(doc, run_ids) if any(state != EXPECT_OK for state in states.values()): raise _Unreadable("exit 0 with a run that is not ok") return LegResult.ok({"ingest_id": _token(doc.get("ingest_id")), "expect": states}) def _refusal_code(stderr: str) -> str: match = _HUB_ERROR_LINE.search(stderr) return ( f"{HUB_FAILED_PREFIX}{match.group(1)}" if match else f"{HUB_EXIT_PREFIX}{HUB_EXIT_REFUSED}" ) def _judge_case(stdout: str, run_ids: Sequence[str]) -> LegResult: doc = _summary(stdout) cases = doc.get("cases") if not isinstance(cases, Mapping) or len(cases) != 1: raise _Unreadable("exit 2 needs exactly one case summary") [case] = cases.values() if not isinstance(case, Mapping): raise _Unreadable("case summary is not an object") detail = {"expect": _expect_states(doc, run_ids)} if "expect" in doc else {} blocked, failed = case.get("blocked"), case.get("failed") if case.get("status") == HUB_CASE_BLOCKED and isinstance(blocked, Mapping): code = f"{CASE_BLOCKED_PREFIX}{_token(blocked.get('code'))}" elif case.get("status") == HUB_CASE_FAILED and isinstance(failed, Mapping): code = f"{CASE_FAILED_PREFIX}{_token(failed.get('stage'), _STAGE)}" else: raise _Unreadable("exit 2 without a blocked or failed case") return LegResult.failed(code, detail=detail) def _judge_expect_failed(stdout: str, run_ids: Sequence[str]) -> LegResult: states = _expect_states(_summary(stdout), run_ids) bad = next((state for state in states.values() if state != EXPECT_OK), None) if bad is None: raise _Unreadable("exit 4 with every run ok") return LegResult.failed(f"{RUN_NOT_OK_PREFIX}{bad}", detail={"expect": states}) def _summary(stdout: str) -> Mapping[str, Any]: """stdout 의 요약 JSON. 앞에 다른 줄이 섞였으면 `{` 로 시작하는 첫 줄부터 읽는다.""" lines = stdout.splitlines(keepends=True) start = next((i for i, line in enumerate(lines) if line.startswith("{")), None) if start is None: raise _Unreadable("no JSON object on stdout") try: doc = json.loads("".join(lines[start:])) except json.JSONDecodeError as exc: raise _Unreadable("summary is not JSON") from exc if not isinstance(doc, Mapping): raise _Unreadable("summary is not an object") return doc def _expect_states(doc: Mapping[str, Any], run_ids: Sequence[str]) -> dict[str, str]: """요청 순서대로 run → 상태. 요청한 run 이 없거나 모르는 상태면 읽을 수 없다.""" expect = doc.get("expect") runs = expect.get("runs") if isinstance(expect, Mapping) else None if not isinstance(runs, Mapping): raise _Unreadable("summary has no expect block") states: dict[str, str] = {} for run_id in run_ids: entry = runs.get(run_id) state = entry.get("state") if isinstance(entry, Mapping) else None if state not in EXPECT_STATES: raise _Unreadable("expect block misses a requested run") states[run_id] = state return states def _token(value: Any, grammar: re.Pattern[str] = _TOKEN) -> str: if not isinstance(value, str) or grammar.fullmatch(value) is None: raise _Unreadable("summary token has an unexpected shape") return value # ── 실행 ───────────────────────────────────────────────────────────────── def run_hub_leg( target: Target, run_ids: Sequence[str], *, confirm_local: bool, child_env: Mapping[str, str] | None = None, secrets: Sequence[str] = (), ) -> LegResult: """`hub ingest --case a/c --expect-run …` 한 번. 예외는 hook 이 `hub_exception:` 으로 강등한다. `child_env` 는 설정 출처 opt-in 일 때만(부모 환경 + URL), 아니면 None(부모 환경 그대로). `secrets` 는 진단 가림 목록. """ ids = _checked_run_ids(run_ids) argv = build_hub_argv(target, ids, confirm_local=confirm_local, env=child_env) cwd = _workspace() if cwd is None: return LegResult.skipped(NO_WORKSPACE) try: result = proc.run_pnpm(argv, cwd=cwd, env=child_env, timeout=HUB_INGEST_TIMEOUT_SECONDS) except FileNotFoundError: return LegResult.failed(PNPM_MISSING) except subprocess.TimeoutExpired as exc: _echo_diagnostics(exc.stderr, secrets) return LegResult.failed(TIMEOUT) leg = _with_run_hint(judge_hub(result, ids), target) if leg.status == STATUS_FAILED: _echo_diagnostics(result.stderr, secrets) return leg def diagnostic_lines(stderr: str | bytes | None, secrets: Sequence[str] = ()) -> list[str]: """hub CLI stderr → 콘솔에 옮길 꼬리(리뷰 지적 6). `[hub]` 줄이 있으면 그 마지막 몇 줄, 없으면 비지 않은 마지막 몇 줄. 줄마다 비밀을 가린 뒤(`status.redact_secrets` — 자르기 전에 가려야 URL 이 중간에 잘려 비밀번호가 새지 않는다) 길이를 자른다. `secrets` 는 환경 변수 밖의 비밀(설정 출처 URL 값). 상태 파일·detail 에는 싣지 않는다(D-L6-4 — 코드만). """ if isinstance(stderr, bytes): stderr = stderr.decode("utf-8", errors="replace") lines = [line.rstrip() for line in (stderr or "").splitlines() if line.strip()] hub_lines = [line for line in lines if line.startswith(_HUB_LOG_PREFIX)] tail = (hub_lines or lines)[-HUB_DIAG_MAX_LINES:] return [_clip(status.redact_secrets(line, secrets)) for line in tail] def _clip(line: str) -> str: return line if len(line) <= HUB_DIAG_MAX_CHARS else f"{line[:HUB_DIAG_MAX_CHARS]}…" def _echo_diagnostics(stderr: str | bytes | None, secrets: Sequence[str] = ()) -> None: lines = diagnostic_lines(stderr, secrets) if not lines: return click.secho(f" hub CLI stderr 마지막 {len(lines)}줄(비밀은 가림):", fg="red", err=True) for line in lines: click.secho(f" {line}", fg="red", err=True) def _workspace(): # 모듈 속성으로 부른다 — 시험이 `target.workspace_root` 를 바꿀 수 있게. return target.workspace_root() def _with_run_hint(leg: LegResult, t: Target) -> LegResult: """`run_not_ok` 면 되살리기에 ok 가 아닌 첫 run 을 적는다(batch 에서 콘솔이 `` 으로 쓰지 않게).""" if not leg.code.startswith(RUN_NOT_OK_PREFIX): return leg states = leg.detail.get("expect") or {} bad = next((run for run, state in states.items() if state != EXPECT_OK), None) if bad is None: return leg hint = console.hub_recovery(leg.code, t.case_ref, bad) return LegResult.failed(leg.code, hint, leg.detail) def ingest_runs( target: Target, run_ids: Sequence[str], *, confirm_local: bool, child_env: Mapping[str, str] | None = None, secrets: Sequence[str] = (), ) -> LegResult: """L6b `runs eval` 새 경로 ④ 가 부르는 적재 — 판정·실행은 `run_hub_leg` 와 같다(게이트는 `hook.gated_hub_leg`).""" return run_hub_leg( target, run_ids, confirm_local=confirm_local, child_env=child_env, secrets=secrets )