"""run 종료 훅 오케스트레이터 (계획 2026-09-27 L6 §2.1 · D-L6-2 · D-L6-3 · D-L6-11 · D-L6-12). 순서 = **번들 → hub**(레거시 적재는 부르지 않는다, D-M2-4 (b)). hub 대상 run 은 case 잠금 **안**에서 두 다리를 돌고 상태 파일을 쓴 뒤 잠금 밖에서 콘솔 요약을 낸다. **예외 봉쇄(D-L6-2 · 검토 F1).** 다리 호출마다 `except Exception` → `failed:_exception:`(타입 이름만). 상태 파일 쓰기 실패는 콘솔 경고로 강등하고, 훅 전체도 한 겹 더 감싸 run 명령이 훅 때문에 종료 1·트레이스백이 되지 않게 한다. batch 에서 훅 예외가 프롬프트 실패로 세지지도 않는다. `BaseException`(KeyboardInterrupt·pytest tripwire)은 잡지 않는다. **예외 상세는 로그로만(리뷰 지적 7).** 콘솔·상태 파일에는 타입 이름만 싣고(D-L6-2), 트레이스백은 이 모듈 로거에 남긴다 — 기본은 DEBUG(보통 설정에서는 보이지 않는다), `SOLAR_EVAL_HOOK_DEBUG=1` 이면 WARNING(stderr). 트레이스백은 입력 조각을 담을 수 있으니 현장 진단 때만 켠다. **스모크 run 은 잠그지 않는다(D-L6-3 "돌 다리가 없으면 잠그지 않는다" · D-L6-10).** hub 대상이어도 `--limit` 스모크면 잠금·상태 파일 없이 두 다리 `skipped:smoke_run` 한 줄로 끝난다 — 다른 훅이 잠금을 쥐고 있어도 기다리거나 `lock_timeout` 이 되지 않는다. 종료 코드는 호출자가 `exit_code_for(result, strict)` 로 정한다 — 기본 0, strict 이고 실패 다리가 있으면 3. **opt-in 한 곳(계획 2026-09-28 L10 §2.6 · D-L10-6).** `gated_hub_leg` 가 `optin.resolve_hub_optin(config=t.hub_config)` 로 환경 변수 > 설정 파일 `hub:` 절을 푼다. 설정 출처면 URL 은 자식 환경(`child_env`)으로만 가고, 설정 값은 진단 가림·상태 파일 거부 목록(`optin.config_secrets`)에 더한다. 호출자(`runs start`·`resume`·batch 끝·`runs eval` 발행) 시그니처는 그대로다. """ from __future__ import annotations import logging from collections.abc import Callable, Sequence from contextlib import ExitStack from datetime import datetime, timezone from pathlib import Path from typing import TYPE_CHECKING from solar_eval.hub_hook import bundle_leg, console, hub_leg, lock, optin, status, target from solar_eval.hub_hook.types import ( BATCH_PENDING, EXIT_HOOK_FAILED, HOOK_LOCK_TIMEOUT_SECONDS, LEG_BUNDLE, LEG_HOOK, LEG_HUB, LEG_LOCK, LEG_STATUS_FILE, LOCK_TIMEOUT, NO_BUNDLE, NO_WORKSPACE, NOT_OPTED_IN, SKIP_STANDALONE, SMOKE_RUN, HookMode, HookOptions, HookResult, LegResult, Skip, Target, bundle_ready, exception_code, hub_run_id, ) if TYPE_CHECKING: from solar_eval.cli.config import CLIConfig _LOG = logging.getLogger(__name__) def _now() -> str: return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") def _contained_code(leg: str, exc: Exception) -> str: """봉쇄한 예외 → 코드(타입 이름만, D-L6-2). 트레이스백은 로거로만 — 콘솔·상태 파일에는 싣지 않는다.""" code = exception_code(leg, exc) level = logging.WARNING if optin.hook_debug_requested() else logging.DEBUG _LOG.log(level, "Experiment Hub 훅 예외 봉쇄 — %s", code, exc_info=exc) return code def _contained(leg: str, fn: Callable[..., LegResult], *args, **kwargs) -> LegResult: """다리 하나를 돌리고 예기치 않은 예외를 `_exception:` 실패로 강등한다(D-L6-2).""" try: return fn(*args, **kwargs) except Exception as exc: # 다리 경계 — 어떤 예외도 run 명령을 실패로 만들지 않는다 return LegResult.failed(_contained_code(leg, exc)) def exit_code_for(result: HookResult | None, strict: bool) -> int: """훅 결과 → run 명령 종료 코드(D-L6-11). 기본 0, strict 이고 실패 다리가 있으면 3.""" return EXIT_HOOK_FAILED if strict and result is not None and not result.ok else 0 def run_hook( cfg: CLIConfig, project: str, run_dir: Path, options: HookOptions ) -> HookResult | None: """run 하나가 끝난 뒤의 훅. hub 대상이 아니면(standalone·`--no-ingest`) None 또는 건너뜀 결과.""" run_id = Path(run_dir).name try: return _run_hook(cfg, project, Path(run_dir), run_id, options) except Exception as exc: # 훅 바깥 겹(D-L6-2) — 콘솔에 알리고 결과로 돌려준다 code = _contained_code(LEG_HOOK, exc) console.echo_hook_crashed(code) return HookResult(run_id, None, {LEG_HOOK: LegResult.failed(code)}) def _run_hook( cfg: CLIConfig, project: str, run_dir: Path, run_id: str, options: HookOptions ) -> HookResult | None: if options.no_ingest: if cfg.repo_root is not None: console.echo_no_ingest(project, run_id, target.case_ref_hint(cfg, project)) return None resolved = target.resolve_target(cfg, project) if isinstance(resolved, Skip): if resolved.code == SKIP_STANDALONE: return None console.echo_skip(resolved, project) legs = { LEG_BUNDLE: LegResult.skipped(resolved.code), LEG_HUB: LegResult.skipped(resolved.code), } return HookResult(run_id, None, legs, _now(), _now()) if options.smoke: # 돌 다리가 없다 — 잠그지 않고 상태 파일도 쓰지 않는다(D-L6-3 · D-L6-10, 리뷰 지적 1). console.echo_smoke(resolved.case_ref) smoke = {LEG_BUNDLE: LegResult.skipped(SMOKE_RUN), LEG_HUB: LegResult.skipped(SMOKE_RUN)} return HookResult(run_id, resolved.case_ref, smoke, _now(), _now()) result = _run_target(resolved, run_dir, run_id, options) console.echo_summary(result, project) return result def _run_target(t: Target, run_dir: Path, run_id: str, options: HookOptions) -> HookResult: """case 잠금 안에서 두 다리 → 상태 파일(D-L6-3). 잠금 한도를 넘기면 두 다리 모두 not_run.""" started = _now() with ExitStack() as stack: try: held = stack.enter_context( lock.case_lock(t.account, t.case, timeout=HOOK_LOCK_TIMEOUT_SECONDS) ) except Exception as exc: # 잠금 파일을 만들 수 없다 — 다리를 돌리지 않는다 legs = _lock_failed(_contained_code(LEG_LOCK, exc)) else: legs = ( _legs_in_lock(t, run_dir, run_id, options) if held else _lock_failed(LOCK_TIMEOUT) ) result = HookResult(run_id, t.case_ref, legs, started, _now()) _write_status(t, result, options) return result def _lock_failed(code: str) -> dict[str, LegResult]: return { LEG_LOCK: LegResult.failed(code), LEG_BUNDLE: LegResult.not_run(), LEG_HUB: LegResult.not_run(), } def _legs_in_lock( t: Target, run_dir: Path, run_id: str, options: HookOptions ) -> dict[str, LegResult]: bundle = _contained(LEG_BUNDLE, bundle_leg.run_bundle_leg, t, run_dir, run_id) if options.mode is HookMode.BATCH_ITEM: hub = LegResult.not_run(BATCH_PENDING) elif not bundle_ready(bundle): hub = LegResult.skipped(NO_BUNDLE) else: # `--expect-run` 은 번들의 run_id(run.json) — 디렉토리 이름과 다를 수 있다(리뷰 지적 3). 상태 파일 이름은 디렉토리 이름. hub = gated_hub_leg(t, (hub_run_id(bundle, run_id),)) return {LEG_BUNDLE: bundle, LEG_HUB: hub} def gated_hub_leg(t: Target, run_ids: Sequence[str]) -> LegResult: """hub 다리 게이트 한 곳 — opt-in(D-L6-4 · L10 D-L10-6)·워크스페이스(C-L6-9)를 본 뒤 `hub_leg.run_hub_leg`(예외 봉쇄). 호출자가 case 잠금을 쥐고 번들 유무를 이미 봤다고 가정한다. L6b `runs eval` 새 경로 ④ 도 이 함수를 부른다. opt-in 해석 경고(설정 모양 오류·에이전트 세션에서 설정 무시)는 건너뛰기 전에 먼저 찍는다 — 값은 싣지 않는다. """ resolved = optin.resolve_hub_optin(config=t.hub_config) for warning in resolved.warnings: console.echo_warning(warning) if not resolved.opted_in: return LegResult.skipped(NOT_OPTED_IN) if target.workspace_root() is None: return LegResult.skipped(NO_WORKSPACE) if resolved.confirm.warning is not None: console.echo_warning(resolved.confirm.warning) return _contained( LEG_HUB, hub_leg.run_hub_leg, t, tuple(run_ids), confirm_local=resolved.confirm.confirm_local, child_env=resolved.child_env, secrets=resolved.secrets, ) def status_secrets(t: Target) -> tuple[str, ...]: """상태 파일 거부 목록에 더할 설정 출처 비밀(§2.6 "비밀") — `runs eval` 발행도 같은 함수를 쓴다.""" return optin.config_secrets(t.hub_config) def _write_status(t: Target, result: HookResult, options: HookOptions) -> None: try: status.write_status( t, result, options.command, strict=options.strict, secrets=status_secrets(t) ) except Exception as exc: # 상태 파일은 보조 기록 — 쓰기 실패는 경고로 강등(D-L6-2) console.echo_status_write_failed(_contained_code(LEG_STATUS_FILE, exc)) def finish_batch( cfg: CLIConfig, project: str, results: Sequence[HookResult | None], options: HookOptions, ) -> LegResult | None: """batch 끝 hub 다리 한 번(D-L6-12) — 번들이 생긴 run 들을 `--expect-run` 으로, case 잠금 안에서. 끝나면 run 마다 상태 파일의 `hub` 를 `status.update_legs` 로 다시 쓴다 — 번들이 없어 끝 다리에 들지 못한 run 은 `skipped:no_bundle` 로(상태 파일에 `batch_pending` 이 남지 않게). 끝 다리를 돌지 않았으면 None. """ try: return _finish_batch(cfg, project, results, options) except Exception as exc: # 훅 바깥 겹(D-L6-2) code = _contained_code(LEG_HOOK, exc) console.echo_hook_crashed(code) return LegResult.failed(code) def _finish_batch( cfg: CLIConfig, project: str, results: Sequence[HookResult | None], options: HookOptions, ) -> LegResult | None: targeted = [r for r in results if r is not None and r.case is not None] ready = [r for r in targeted if bundle_ready(r.legs.get(LEG_BUNDLE))] # 번들이 없어 끝 다리에 들지 못한 run — 상태 파일의 `batch_pending` 을 `no_bundle` 로 닫는다(l6a-verify). no_bundle = [r.run_id for r in targeted if r not in ready and _hub_pending(r)] if options.no_ingest or not (ready or no_bundle): return None resolved = target.resolve_target(cfg, project) if isinstance(resolved, Skip): return None # `--expect-run` 은 번들의 run_id(run.json), 상태 파일은 디렉토리 이름(리뷰 지적 3). expect = [hub_run_id(r.legs.get(LEG_BUNDLE), r.run_id) for r in ready] leg: LegResult | None = None with lock.case_lock(resolved.account, resolved.case, timeout=HOOK_LOCK_TIMEOUT_SECONDS) as held: if ready: leg = gated_hub_leg(resolved, expect) if held else LegResult.failed(LOCK_TIMEOUT) for result in ready: _update_hub_leg(resolved, result.run_id, leg) for run_id in no_bundle: _update_hub_leg(resolved, run_id, LegResult.skipped(NO_BUNDLE)) if leg is not None: console.echo_batch_hub(leg, resolved.case_ref, expect) return leg def _hub_pending(result: HookResult) -> bool: """batch 한 run 의 hub 다리가 끝 다리를 기다리는 중인가(`not_run:batch_pending`).""" hub = result.legs.get(LEG_HUB) return hub is not None and hub.code == BATCH_PENDING def _update_hub_leg(t: Target, run_id: str, leg: LegResult) -> None: try: status.update_legs(t, run_id, {LEG_HUB: leg}, secrets=status_secrets(t)) except Exception as exc: # 상태 파일 보조 기록 — 경고로 강등(D-L6-2) console.echo_status_write_failed(_contained_code(LEG_STATUS_FILE, exc))