hf2q 0.1.30

Pure Rust CLI for converting HuggingFace models to hardware-optimized formats and serving them over an OpenAI-compatible API on Apple Silicon
"""Join quality evidence to the frozen arm's actual Q5 launch."""
import hashlib
import json
import re
from pathlib import Path

import q5_calibration
import q5_case
import q5_runtime
import q5_policy


def require(condition, message):
    if not condition:
        raise ValueError(message)


def bound_json(path, digest):
    raw = Path(path).read_bytes()
    require(hashlib.sha256(raw).hexdigest() == digest, "quality launch input changed")
    return json.loads(raw)


def source_population(bindings, expected):
    require(isinstance(bindings, dict) and bindings and
            all(isinstance(path, str) and Path(path).is_absolute() and
                isinstance(digest, str) and re.fullmatch(r"[0-9a-f]{64}", digest)
                for path, digest in bindings.items()), "Native9 source bindings malformed")
    sources = {Path(path).name: digest for path, digest in bindings.items()}
    require(len(sources) == len(bindings) and set(sources) == expected,
            "Native9 source population is incomplete or foreign")
    return sources


def validate_sources(identity):
    bindings = identity.get("supervisor_source_bindings")
    sources = source_population(bindings, {path.name for path in q5_calibration.source_paths()})
    require(identity.get("supervisor_sources") == sources, "Native9 logical source map differs")
    native_names = {Path(path).name for path in q5_runtime.source_bindings()}
    native = identity.get("native_ownership_sources")
    source_population(native, native_names)
    require(native == {path: digest for path, digest in bindings.items() if Path(path).name in native_names},
            "Native9 ownership source bindings differ")


def validate_cleanup(cleanup, launches):
    """Check complete empty/reaped evidence for each registered kernel root."""
    require(isinstance(cleanup, dict) and all(isinstance(launch, dict) for launch in launches),
            "Native9 cleanup evidence malformed")
    roots = cleanup.get("root_identities", [])
    require(isinstance(roots, list) and all(isinstance(root, dict) for root in roots),
            "Native9 cleanup roots malformed")
    require(cleanup.get("schema") == q5_runtime.OWNERSHIP_SCHEMA and
            cleanup.get("proven") is True and cleanup.get("remaining") == [] and
            cleanup.get("errors") == [] and cleanup.get("refused_pgids") == [] and
            cleanup.get("direct_child_reaped") is True and
            type(cleanup.get("empty_ns")) is int and cleanup["empty_ns"] > 0 and
            type(cleanup.get("native_observations")) is int and cleanup["native_observations"] > 0 and
            isinstance(cleanup.get("signal_events"), list) and len(roots) == len(launches) and
            len({root.get("pid") for root in roots}) == len(roots),
            "Native9 cleanup is unproven")
    for launch in launches:
        root = launch.get("root_identity") or {}
        require(root in roots and root in cleanup.get("known_identities", []) and
                type(root.get("pid")) is int and root["pid"] > 1 and root.get("pgid") == root["pid"] and
                isinstance(root.get("lifetime_id"), str) and re.fullmatch(r"darwin-unique:[1-9][0-9]*", root["lifetime_id"]) and
                isinstance(root.get("parent_lifetime_id"), str) and
                re.fullmatch(r"darwin-unique:[1-9][0-9]*", root["parent_lifetime_id"]) and
                type(root.get("pid_version")) is int and
                type(launch.get("registered_ns")) is int and 0 < launch["registered_ns"] <= cleanup["empty_ns"],
                "Native9 registered kernel lifetime is missing")


def validate_ownership(receipt):
    cleanup = receipt.get("cleanup") or {}
    launches = [(receipt.get("server") or {}).get("native_launch") or {},
                receipt.get("client_native_launch") or {}]
    require(receipt.get("cleanup_proven") is True, "Native9 cleanup is unproven")
    validate_cleanup(cleanup, launches)
    for launch, process in zip(launches, (receipt["server"], receipt["client"])):
        require(launch["root_identity"]["pid"] == process["pid"], "Native9 process root differs")


def validate_runner(record, bindings, *, allow_memory_stop=False):
    source_population(bindings, {path.name for path in q5_calibration.source_paths()})
    reference = record.get("runner_ownership")
    require(isinstance(reference, dict), "outer Native9 evidence missing")
    proof = bound_json(reference["path"], reference["sha256"])
    launch = proof.get("launch") or {}
    stop = proof.get("stop")
    allowed = stop is None or (allow_memory_stop and isinstance(stop, dict) and
                               stop.get("reason") in q5_policy.MEMORY_STOPS)
    require(proof.get("argv") == record["argv"] and allowed and
            proof.get("source_bindings") == bindings and launch.get("exec_argv") == record["argv"],
            "outer Native9 invocation or source bindings differ")
    gate = launch.get("gate_argv") or []
    native_path = next(path for path in bindings if Path(path).name == "native_owned.py")
    require(len(gate) == len(record["argv"]) + 8 and
            all(isinstance(arg, str) for arg in gate) and Path(gate[0]).is_absolute() and
            gate[1:4] == ["-E", "-s", "-B"] and gate[4] == native_path and
            gate[5] == "--exec-gate" and gate[6].isdecimal() and gate[7] == "--" and
            gate[8:] == record["argv"], "outer Native9 registered exec gate differs")
    validate_cleanup(proof.get("cleanup") or {}, [launch])


def validate(case, overrides, record, receipt, summary, summary_path, source_identity):
    """Rebuild the scheduled arm, using only its launch-bound runtime identities."""
    validate_sources(source_identity)
    for key in ("supervisor_sources", "supervisor_source_bindings", "native_ownership_sources"):
        require(bool(source_identity.get(key)) and receipt.get(key) == source_identity[key],
                "quality " + key + " differs from the independently frozen sources")
    validate_ownership(receipt)
    validate_runner(record, source_identity["supervisor_source_bindings"])
    output = Path(record["output"]).resolve()
    case_path = Path(record["case"]).resolve()
    require(Path(receipt["case"]["path"]).resolve() == case_path and
            receipt["case"]["sha256"] == record["case_sha256"], "quality receipt case differs")
    require(bound_json(case_path, record["case_sha256"]) == case, "quality derived case differs")
    expected_summary = Path(q5_case.expand(case["client"]["summary"], {"OUT": str(output)})).resolve()
    require(Path(summary_path).resolve() == expected_summary and
            Path(receipt["client"]["summary_path"]).resolve() == expected_summary,
            "quality summary is not the launched client's output")

    approval_path = output / "client-approval.json"
    approval_raw = approval_path.read_bytes()
    approval_sha = hashlib.sha256(approval_raw).hexdigest()
    approval = json.loads(approval_raw)
    argv = record["argv"]
    driver = Path(argv[2]).resolve()
    require(driver.name == "q5_calibration.py" and Path(argv[0]).is_absolute() and
            Path(argv[3]).resolve() == case_path and
            hashlib.sha256(driver.read_bytes()).hexdigest() == receipt["supervisor_sources"]["q5_calibration.py"],
            "quality Q5 invocation/source differs")
    # Replay capture identities, not the report consumer's checkout/interpreter.
    builtins = {"REPO": str(driver.parents[2]), "OUT": str(output), "PYTHON": argv[0],
                "PYTHON_SHA256": hashlib.sha256(Path(argv[0]).resolve().read_bytes()).hexdigest(),
                "RUN_ID": approval["run_id"], "NONCE32": approval["barrier_token"]}
    environ = {q5_case.OVERRIDE_PREFIX + key: value for key, value in overrides.items()}
    plan = q5_case.build_plan(case, builtins, environ)
    require(plan["complete"] and hashlib.sha256(json.dumps(plan, sort_keys=True).encode()).hexdigest()
            == receipt["plan_sha256"], "quality launch differs from the frozen arm configuration")
    require(receipt["serve_argv"] == plan["serve"]["argv"] and
            receipt["serve_env"] == plan["serve"]["env"], "quality server launch differs")
    pid = receipt["server"]["pid"]
    require(type(pid) is int and pid > 0 and summary["server_pid"] == approval["server_pid"] == pid and
            summary["run_id"] == approval["run_id"], "quality client/server run identity differs")
    values, missing = q5_case.resolve_variables(case, builtins, environ)
    require(not missing, "quality launch has unresolved inputs")
    values.update(SERVED_MODEL=plan["served_model"], SERVER_PID=pid,
                  CLIENT_APPROVAL=str(approval_path), CLIENT_APPROVAL_SHA256=approval_sha)
    require(receipt["client_argv"] == q5_case.expand(plan["client"]["argv"], values),
            "quality client launch/approval differs")
    spec = plan["client"]["approval"]
    expected = bound_json(spec["template"], receipt["inputs"][spec["template"]])
    require("peer_supervised_launch" not in expected and "peer_supervised_launch" not in spec["set"],
            "quality peer launch cannot be supplied by the approval template")
    expected.update({key: q5_calibration.resolve_set(value, values) for key, value in spec["set"].items()})
    if expected.get("peer_reference") is not None:
        expected["peer_supervised_launch"] = {
            "schema": "hf2q.peer.supervised-launch.v1", "server_pid": pid,
            "base_url": expected["base_url"], "binary": plan["binary"],
            "binary_sha256": receipt["binary"]["sha256"], "serve_argv": receipt["serve_argv"]}
    require(approval == expected, "quality approval differs from the launched frozen case")