"""``explicit-c2`` — independent dual-compile of a candidate (``docs/02`` §7). The one implemented subcommand, ``dual-compile``, runs the C2 compiler over a single candidate described by a JSON file: it builds the two pinned model clients (proposer = Qwen3.5-9B, verifier = Gemma-4-12B-it) from the resource manifest, sends the §7.1 independent request to each, and reconciles their outputs through the §7.2/§7.3 gate. The two ``compiled_program`` records and the :class:`C2Outcome` are written to ``--output``. Model calls go through the real :class:`HfModelClient`, which is **gated and never fakes a response**: when a pinned snapshot is absent, LFS-pointer-only, or the accelerator/``transformers`` stack is missing, it raises :class:`ModelUnavailable`. The CLI surfaces that as exit code ``2`` with a ``BLOCKED`` notice — the candidate is skipped, never substituted (runbook: blocked → skip, never replace). A successful dual-compile exits ``0``; a bad candidate/config exits ``1``. Candidate sourcing at scale (selecting ChartQA-H / MMK12 / MMR1-RL / MMMU rows and building their worlds) is the P11 assembler; this driver consumes one candidate from disk so the gate is exercisable end-to-end before P11 lands. """ from __future__ import annotations import argparse import json import sys from pathlib import Path from typing import Any from ..c2 import C2Candidate, C2Compiler, ModelUnavailable from ..c2.client import HfModelClient from ..config import ConfigError, load_resources from ..hashing import choices_sha256, question_sha256 from ..paths import repo_root from ..resources import plan from ._stub import dispatch _PROG = "explicit-c2" _SUBCOMMANDS = { "dual-compile": "Run the §7 independent dual-compile over one candidate (P4).", } # Roles pinned in ``configs/resources.yaml`` (ADR-0002). _PROPOSER_ROLE = "program_proposer" _VERIFIER_ROLE = "independent_program_verifier" def _utc_now() -> str: from datetime import UTC, datetime return datetime.now(tz=UTC).strftime("%Y-%m-%dT%H:%M:%SZ") def _load_resources(path: Path) -> Any: try: return load_resources(path) except (ConfigError, FileNotFoundError) as exc: print(f"{_PROG} dual-compile: resources load failed: {exc}", file=sys.stderr) raise _Handled(1) from exc class _Handled(Exception): """Internal signal that a nonzero exit has already been printed.""" def __init__(self, code: int) -> None: super().__init__() self.code = code def _model_client(resources: Any, role: str, resources_path: Path) -> HfModelClient: """Build the :class:`HfModelClient` for the manifest entry with ``role``. Raises :class:`_Handled(1)` if no entry (or more than one) carries the role. """ matches = [ref for ref in plan(resources) if ref.kind == "model" and ref.role == role] if not matches: disabled_role = f"disabled_future_c2_{role}" disabled = [ entry for entry in resources.models.values() if getattr(entry, "role", None) == disabled_role ] if disabled: print( f"{_PROG} dual-compile: BLOCKED — {role!r} is disabled for the v1 release", file=sys.stderr, ) raise _Handled(2) print( f"{_PROG} dual-compile: no model with role {role!r} in {resources_path}", file=sys.stderr, ) raise _Handled(1) if len(matches) > 1: print( f"{_PROG} dual-compile: multiple models with role {role!r}; expected exactly one", file=sys.stderr, ) raise _Handled(1) ref = matches[0] return HfModelClient( logical_name=ref.logical_name, repo_id=ref.repo_id, revision=ref.revision, local_path=ref.local_path, ) def _load_candidate(path: Path) -> C2Candidate: """Parse a candidate JSON file into a :class:`C2Candidate`. The file carries ``base_id``, ``dsl``, ``question_text``, ``choices`` (``[{key, text}, ...]``), ``image_sha256``, and ``world``. The question/ choices hashes are computed from the text when not supplied, so the caller cannot accidentally desync them. """ try: raw = json.loads(path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as exc: print(f"{_PROG} dual-compile: cannot read candidate {path}: {exc}", file=sys.stderr) raise _Handled(1) from exc if not isinstance(raw, dict): print(f"{_PROG} dual-compile: candidate must be a JSON object: {path}", file=sys.stderr) raise _Handled(1) base_id = raw.get("base_id") dsl = raw.get("dsl") question_text = raw.get("question_text") choices_raw = raw.get("choices") world = raw.get("world") if not (isinstance(base_id, str) and isinstance(dsl, str) and isinstance(question_text, str)): print( f"{_PROG} dual-compile: candidate needs string base_id, dsl, question_text: {path}", file=sys.stderr, ) raise _Handled(1) if dsl not in ("plotqa_dsl_v1", "geometry_dsl_v1", "table_dsl_v1"): print(f"{_PROG} dual-compile: unknown dsl {dsl!r}: {path}", file=sys.stderr) raise _Handled(1) if not isinstance(choices_raw, list) or not isinstance(world, dict): print( f"{_PROG} dual-compile: candidate needs list 'choices' and object 'world': {path}", file=sys.stderr, ) raise _Handled(1) choices: tuple[tuple[str, str], ...] = tuple( (str(c["key"]), str(c["text"])) for c in choices_raw ) q_sha = raw.get("question_sha256") or question_sha256(question_text) c_sha = raw.get("choices_sha256") or choices_sha256([{"key": k, "text": t} for k, t in choices]) return C2Candidate( base_id=base_id, dsl=dsl, # type: ignore[arg-type] question_sha256=q_sha, choices_sha256=c_sha, question_text=question_text, choices=choices, image_sha256=str(raw.get("image_sha256", "")), world=world, ) def _outcome_to_json(outcome: Any) -> dict[str, Any]: """Serialize a :class:`C2Outcome` to a JSON-safe dict.""" return { "state": outcome.state, "accepted": outcome.accepted, "reason": outcome.reason, "canonical_hash_proposer": outcome.canonical_hash_proposer, "canonical_hash_verifier": outcome.canonical_hash_verifier, "full_answer_proposer": list(outcome.full_answer_proposer) if outcome.full_answer_proposer is not None else None, "full_answer_verifier": list(outcome.full_answer_verifier) if outcome.full_answer_verifier is not None else None, "mutation_evidence": [ { "leaf": e.leaf, "kind": e.kind, "description": e.description, "proposer_status": e.proposer_status, "proposer_answer": e.proposer_answer, "verifier_status": e.verifier_status, "verifier_answer": e.verifier_answer, "agree": e.agree, } for e in outcome.mutation_evidence ], "proposer_record": outcome.proposer_record, "verifier_record": outcome.verifier_record, } def cmd_dual_compile(argv: list[str]) -> int: parser = argparse.ArgumentParser(prog=f"{_PROG} dual-compile") parser.add_argument( "--candidate", type=Path, required=True, help="candidate JSON file (§7.1 evidence)." ) parser.add_argument( "--resources", type=Path, default=repo_root() / "configs" / "resources.yaml", ) parser.add_argument("--output", type=Path, required=True, help="output JSON path.") parser.add_argument("--seed", type=int, default=0, help="deterministic mutation-suite seed.") args = parser.parse_args(argv) try: resources = _load_resources(args.resources) candidate = _load_candidate(args.candidate) proposer = _model_client(resources, _PROPOSER_ROLE, args.resources) verifier = _model_client(resources, _VERIFIER_ROLE, args.resources) except _Handled as exc: return exc.code compiler = C2Compiler(proposer=proposer, verifier=verifier) try: outcome = compiler.compile(candidate, seed=args.seed) except ModelUnavailable as exc: # Blocked → skip, never substitute (runbook). Surface as exit 2, not a # faked success and not a silent empty output. print(f"{_PROG} dual-compile: BLOCKED — model unavailable: {exc}", file=sys.stderr) return 2 payload = { "schema_version": 1, "produced_at": _utc_now(), "candidate_base_id": candidate.base_id, "seed": args.seed, "outcome": _outcome_to_json(outcome), } args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(json.dumps(payload, indent=2, sort_keys=True), encoding="utf-8") print( json.dumps( {"state": outcome.state, "accepted": outcome.accepted, "output": str(args.output)}, sort_keys=True, ) ) return 0 _IMPLEMENTATIONS = { "dual-compile": cmd_dual_compile, } def main(argv: list[str] | None = None) -> int: # When invoked as a console entry point, ``argv`` is ``None`` and the real # arguments live on ``sys.argv``. Fall back to those (rather than the empty # list the stub dispatcher treats as "no subcommand") so the ``explicit-c2`` # script is genuinely usable — never a faked success. if argv is None: argv = sys.argv[1:] return dispatch(_PROG, argv, _SUBCOMMANDS, _IMPLEMENTATIONS) if __name__ == "__main__": raise SystemExit(main())