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
"""Engine-free replay of recorded mounted diagnostic disk custody and charges.

Private producer sources are authenticated as bytes, never imported or executed.
Recorded kernel metadata is checked against the producer's authenticated contract;
no live Darwin mount probe is needed by this offline consumer.
"""
import hashlib
import json
from pathlib import Path
import plistlib
import re

from c2_controller_state_authority import authority, check_sources, closed, file_bytes
from c2_matrix_io import META_LIMIT, integer, require, stamp
from c2_observation import regular_evidence

SCHEMA = "hf2q.private.c2-diagnostic-mounted-disk.v1"
GLOBAL_DISK_LIMIT = 843671408455


def logical_disk(root):
    root = Path(root)
    require(root.is_absolute() and root.resolve(strict=True) == root and not root.is_symlink(),
            "canonical logical disk root required")
    if root.is_file():
        return root.stat().st_size
    require(root.is_dir(), "logical disk root absent")
    total = 0
    for path in root.rglob("*"):
        require(not path.is_symlink(), "logical disk symlink/alias refused")
        if path.is_file():
            total += path.stat().st_size
    return total


def working_roots(prepared):
    """Charge the union of claim/config and prepared/outer parents exactly once."""
    config = Path(prepared["config_binding"]["path"])
    output = Path(prepared["output"])
    require(config.is_absolute() and config.resolve(strict=True) == config
            and output.is_absolute() and output.name == "attempt"
            and output.resolve(strict=False) == output,
            "canonical diagnostic working metadata/output paths required")
    roots = tuple(sorted({config.parent, output.parent}))
    for root in roots:
        require(root.resolve(strict=False) == root and (not root.exists() or root.is_dir()),
                "diagnostic working metadata root aliases or is not a directory")
    return tuple(root for root in roots
                 if not any(root != other and root.is_relative_to(other) for other in roots))


def working_disk(prepared):
    return sum(logical_disk(root) for root in working_roots(prepared))


def retained_inventory(reference):
    """Read a bounded index and bounded per-root inventories, charging all bytes."""
    metadata_files, metadata_bytes = {}, 0

    def document(binding):
        nonlocal metadata_bytes
        closed(binding, "path sha256", "retained inventory metadata binding")
        path = Path(binding["path"])
        require(path.is_absolute() and path.resolve(strict=True) == path
                and path.is_file() and str(path) not in metadata_files,
                "distinct canonical retained inventory metadata required")
        raw = file_bytes(binding, META_LIMIT)
        metadata_files[str(path)] = binding["sha256"]
        metadata_bytes += len(raw)
        return json.loads(raw)

    index = closed(document(reference), "schema roots", "retained inventory index")
    require(index["schema"] == "hf2q.private.c2-retained-diagnostic-outputs.v3"
            and type(index["roots"]) is dict and index["roots"], "complete bounded retained inventory index absent")
    roots = {}
    for name, record in index["roots"].items():
        root = Path(name)
        require(root.is_absolute() and str(root) == name and root.resolve(strict=True) == root
                and (root.is_dir() or root.is_file()), "canonical retained inventory root required")
        closed(record, "bytes inventory", "retained root index record")
        size = integer(record["bytes"], "retained root payload bytes")
        inventory = closed(document(record["inventory"]), "schema root bytes file_sha256", "retained root inventory")
        require(inventory["schema"] == "hf2q.private.c2-retained-root-inventory.v1"
                and inventory["root"] == name and integer(inventory["bytes"], "retained inventory payload bytes") == size
                and type(inventory["file_sha256"]) is dict, "retained index/root inventory identity or byte join differs")
        roots[name] = {"bytes": size, "file_sha256": inventory["file_sha256"]}
    require(all(not Path(path).is_relative_to(Path(root)) for path in metadata_files for root in roots),
            "retained inventory metadata overlaps a payload root")
    return {"roots": roots, "bytes": sum(record["bytes"] for record in roots.values()) + metadata_bytes,
            "metadata_files": metadata_files, "metadata_bytes": metadata_bytes}


def retained_disk_checked(prepared):
    reference = prepared["config"]["retained_outputs"]
    manifest = retained_inventory(reference)
    roots = [Path(path) for path in manifest["roots"]]
    current = working_roots(prepared)
    require(all(not Path(path).is_relative_to(root) for path in manifest["metadata_files"] for root in current),
            "retained inventory metadata overlaps current working output")
    for index, root in enumerate(roots):
        require(all(root != live and not root.is_relative_to(live) and not live.is_relative_to(root)
                    for live in current)
                and all(not root.is_relative_to(other) and not other.is_relative_to(root) for other in roots[:index]),
                "retained logical disk roots overlap/refund current working metadata/output")
        record = closed(manifest["roots"][str(root)], "bytes file_sha256", "retained logical disk root")
        actual_paths = {str(root)} if root.is_file() else {str(path) for path in root.rglob("*") if path.is_file()}
        require(actual_paths == set(record["file_sha256"]) and logical_disk(root) == record["bytes"],
                "complete retained logical disk inventory/bytes changed")
        check_sources(record["file_sha256"])
    total = manifest["bytes"]
    require(prepared["retained_outputs"] == {"record": reference, "bytes": total},
            "prepared complete retained output charge differs")
    policy, allocation = prepared["policy"], prepared["allocation"]
    require(total + allocation["disk_upper_bytes"] <= min(GLOBAL_DISK_LIMIT, policy["paired_disk_working_limit_bytes"]),
            "aggregate retained+transient raw logical disk ceiling breached")


def prepared_sources_checked(prepared):
    """Authenticate each complete owner without flattening its bindings twice."""
    check_sources(prepared["file_sha256"])
    check_sources(prepared["plan"]["transitive"])
    retained_disk_checked(prepared)


def encoded(row):
    return (json.dumps(row, sort_keys=True, separators=(",", ":"), allow_nan=False) + "\n").encode()


def producer_contract(prepared, monitor):
    predecessor = authority(prepared["config"]["production_predecessor"])
    require(predecessor["schema"] == "hf2q.private.c2-diagnostic-production-predecessor.v1",
            "mandatory mounted production predecessor absent")
    producer_ref = predecessor["producer_request"]
    producer = authority(producer_ref)
    request_ref = producer["disk_request"]
    request = authority(request_ref)
    contract_ref = request["contract"]
    contract = authority(contract_ref)
    sources = contract["sources"]
    helper = sources["explicit_namespace_binding"]
    binding = dict(producer_request=producer_ref, disk_request=request_ref, contract=contract_ref, helper=helper)
    require(binding == prepared["disk_binding"] == monitor["binding"]
            and Path(helper["path"]).name == "disk_binding.py",
            "actual producer/prepared/receipt mounted helper binding differs")
    files = producer["file_sha256"]
    require(all(files.get(ref["path"]) == ref["sha256"]
                for ref in (request_ref, contract_ref, *sources.values())),
            "producer source map does not authenticate mounted contract closure")
    check_sources(files)
    require(request["schema"] == "hf2q.private.c2-runtime-disk-request.v1"
            and contract["schema"] == "hf2q.private.c2-runtime-disk-contract.v1",
            "actual mounted request/contract schema differs")
    topology = closed(contract["mounted_image_topology"],
        "evidence_mount evidence_device volume_uuid volume_node container physical_store backing_mount backing_device image_path",
        "authenticated mounted topology")
    require(contract["required_volume"] == topology["evidence_mount"]
            and Path(contract["external_root"]).is_relative_to(topology["evidence_mount"])
            and Path(helper["path"]).parent == Path(contract["external_root"])
            and Path(sources["captured_kernel_topology"]["path"]).parent == Path(contract["external_root"])
            and Path(topology["image_path"]).is_relative_to(topology["backing_mount"]),
            "contract mounted namespace/topology differs")
    return binding, contract


def evidence_metadata(volume, image, topology):
    expected = dict(MountPoint=topology["evidence_mount"], DeviceNode=topology["volume_node"],
        VolumeUUID=topology["volume_uuid"], FilesystemType="apfs", BusProtocol="Disk Image",
        ParentWholeDisk=topology["container"], APFSContainerReference=topology["container"],
        APFSPhysicalStores=[{"APFSPhysicalStore": topology["physical_store"]}])
    require(all(volume.get(key) == value for key, value in expected.items()),
            "recorded mounted APFS UUID/device/container/store differs")
    store = re.fullmatch(r"(.+)s[0-9]+", topology["physical_store"])
    require(store is not None, "mounted physical store partition absent")
    entities = image.get("system-entities", [])
    require(image.get("image-path") == topology["image_path"] and image.get("writeable") is True
            and image.get("image-type") == "sparse disk image"
            and any(row.get("dev-entry") == topology["volume_node"]
                    and row.get("mount-point") == topology["evidence_mount"] for row in entities)
            and {"/dev/" + store[1], "/dev/" + topology["physical_store"], "/dev/" + topology["container"]}
                <= {row.get("dev-entry") for row in entities},
            "recorded image does not back authenticated APFS device map")


def custody_checked(custody, contract):
    closed(custody, "snapshot live_volume live_image live_backing captured_metadata captured_metadata_source", "mounted custody")
    topology = contract["mounted_image_topology"]
    capture_ref = contract["sources"]["captured_kernel_topology"]
    require(custody["captured_metadata_source"] == capture_ref, "captured topology source differs")
    pieces = file_bytes(capture_ref).split(b"<?xml")
    require(len(pieces) == 3 and not pieces[0].strip(), "exact two captured kernel plists required")
    volume, images = [plistlib.loads(b"<?xml" + piece) for piece in pieces[1:]]
    matches = [image for image in images["images"] if image.get("image-path") == topology["image_path"]]
    require(len(matches) == 1, "captured mounted image missing or ambiguous")
    evidence_metadata(volume, matches[0], topology)
    require(custody["captured_metadata"] == dict(volume=volume, image=matches[0]),
            "recorded custody differs from authenticated captured kernel plists")
    evidence_metadata(custody["live_volume"], custody["live_image"], topology)
    backing = custody["live_backing"]
    require(backing.get("MountPoint") == topology["backing_mount"] and backing.get("Internal") is False
            and backing.get("BusProtocol") not in (None, "", "Disk Image")
            and backing.get("SolidState") is True and backing.get("WritableVolume") is True,
            "recorded backing is not writable external physical SSD")
    snapshot = closed(custody["snapshot"],
        "symlinks evidence_device evidence_inode backing_device backing_inode image_device image_inode image_regular evidence_mount backing_mount evidence_ismount backing_ismount evidence_uuid",
        "mounted snapshot")
    for field in ("evidence_device", "evidence_inode", "backing_device", "backing_inode", "image_device", "image_inode"):
        integer(snapshot[field], "recorded mounted " + field, 1)
    for name in ("evidence_mount", "backing_mount"):
        mount = closed(snapshot[name], "mount_on mount_from filesystem fsid", "kernel mount identity")
        require(type(mount["fsid"]) is list and len(mount["fsid"]) == 2
                and all(type(value) is int for value in mount["fsid"]), "kernel filesystem identity absent")
    require(snapshot["symlinks"] == [] and snapshot["image_regular"] is True
            and snapshot["evidence_ismount"] is True and snapshot["backing_ismount"] is True
            and snapshot["evidence_device"] == topology["evidence_device"]
            and snapshot["backing_device"] == snapshot["image_device"] == topology["backing_device"]
            and snapshot["evidence_uuid"] == topology["volume_uuid"]
            and snapshot["evidence_mount"]["mount_on"] == topology["evidence_mount"]
            and snapshot["evidence_mount"]["mount_from"] == topology["volume_node"]
            and snapshot["evidence_mount"]["filesystem"] == "apfs"
            and snapshot["backing_mount"]["mount_on"] == topology["backing_mount"]
            and snapshot["backing_mount"]["mount_from"] == backing.get("DeviceNode")
            and dict(device=snapshot["image_device"], inode=snapshot["image_inode"]) == contract["prepared_image_identity"],
            "recorded mount/image inode/physical backing custody differs")
    return snapshot


def disk_bounds(used, internal, external, backing, pending, prepared):
    allocation, policy = prepared["allocation"], prepared["policy"]
    retained = integer(prepared["retained_outputs"]["bytes"], "retained disk bytes")
    for value in (used, internal, external, backing, pending):
        integer(value, "independent disk observation/charge")
    cap = integer(allocation["disk_upper_bytes"], "diagnostic disk grant", 1)
    internal_floor = integer(allocation["internal_free_floor_bytes"], "internal disk floor", 12 << 30)
    output_floor = integer(allocation["output_free_floor_bytes"], "output disk floor", 12 << 30)
    require(used + pending <= cap and retained + cap <= min(GLOBAL_DISK_LIMIT, policy["paired_disk_working_limit_bytes"]),
            "complete retained/current/pending/log disk grant or paired/global ceiling breached")
    reserve = output_floor + max(0, cap - used)
    require(internal >= internal_floor, "recorded internal filesystem free floor breached")
    require(external >= reserve, "recorded APFS complete remaining output reserve breached")
    require(backing >= reserve, "recorded physical backing SSD complete remaining output reserve breached")


def read_rows(path, maximum):
    require(path.is_absolute() and path.resolve(strict=True) == path, "canonical mounted journal path required")
    with regular_evidence(path) as stream:
        before = stream.fileno()
        import os
        info = os.fstat(before)
        require(0 < info.st_size <= maximum, "mounted journal exceeds diagnostic disk grant")
        raw = stream.read(maximum + 1)
        require(len(raw) == info.st_size and stamp(os.fstat(before)) == stamp(info), "mounted journal changed while reading")
    rows = [json.loads(line) for line in raw.splitlines()]
    require(raw == b"".join(encoded(row) for row in rows), "canonical complete mounted journal bytes required")
    return raw, rows


def journal_checked(rows, expected, binding, custody, prepared):
    require(len(rows) == len(expected), "complete exact mounted disk sample/publication coverage required")
    snapshot = custody["snapshot"]
    output = Path(prepared["output"])
    require(all(root.is_relative_to(snapshot["evidence_mount"]["mount_on"]) for root in working_roots(prepared)),
            "diagnostic working metadata/output outside recorded APFS mount")
    previous, end = None, 0
    for index, (row, (phase, sample_ns, owned)) in enumerate(zip(rows, expected)):
        closed(row, "schema index previous_sha256 phase sample_ns begin_ns end_ns snapshot_before snapshot_after output output_device owned_output_bytes pending_bytes log_bytes initial_custody binding internal_free_bytes external_free_bytes physical_backing_free_bytes", "mounted disk observation")
        begin = integer(row["begin_ns"], "mounted observation begin")
        finish = integer(row["end_ns"], "mounted observation end", begin)
        require(row["schema"] == SCHEMA and type(row["index"]) is int and row["index"] == index
                and row["previous_sha256"] == previous and row["phase"] == phase
                and row["sample_ns"] == sample_ns and begin >= end
                and (owned is None or row["owned_output_bytes"] == owned),
                "ordered one-to-one memory/mounted disk sample coverage differs")
        if sample_ns is not None:
            integer(row["sample_ns"], "joined mounted sample time")
            require(sample_ns <= begin and finish - sample_ns <= prepared["policy"]["measured_admission"]["max_sample_gap_ns"],
                    "stale mounted disk observation for memory sample")
        require(row["initial_custody"] == (custody if index == 0 else None)
                and row["binding"] == (binding if index == 0 else None)
                and row["snapshot_before"] == snapshot == row["snapshot_after"]
                and row["output"] == str(output) and row["output_device"] == snapshot["evidence_device"],
                "mounted initial/before/after custody or producer/output binding differs")
        size = integer(row["log_bytes"], "exact mounted journal byte charge", 1)
        pending = integer(row["pending_bytes"], "pending publication disk charge")
        require(size == len(encoded(row)), "actual mounted journal bytes not completely charged")
        disk_bounds(row["owned_output_bytes"], row["internal_free_bytes"], row["external_free_bytes"],
                    row["physical_backing_free_bytes"], pending + size, prepared)
        previous, end = hashlib.sha256(encoded(row)).hexdigest(), finish


def mounted_attempt(receipt, prepared, series, actual_bytes):
    """Mandatory measured-attempt consumer, including both publication journals."""
    monitor = closed(receipt["disk_monitor"], "binding custody raw_path prefix_bytes prefix_sha256 prefix_observations", "mounted receipt monitor")
    binding, contract = producer_contract(prepared, monitor)
    custody_checked(monitor["custody"], contract)
    root = Path(prepared["output"])
    path = root / "mounted-disk-observations.jsonl"
    require(monitor["raw_path"] == str(path), "receipt mounted journal namespace differs")
    expected = [("baseline", entry["sample"]["start_ns"], entry["owned_output_bytes"])
                for entry in receipt["baseline_observations"]]
    expected += [("prelaunch", receipt["prelaunch_observation"]["start_ns"], receipt["admission_reservation"]["live_output_bytes"])]
    expected += [("runtime", receipt["spawn_ns"] + row["t_ns"], row["owned_output_bytes"]) for row in series]
    expected += [("memory-series", None, None), ("terminal", receipt["terminal_observation"]["start_ns"], None),
                 ("receipt-reservation", None, None), ("receipt-staged", None, None), ("receipt-published", None, None)]
    raw, rows = read_rows(path, prepared["allocation"]["disk_upper_bytes"])
    journal_checked(rows, expected, binding, monitor["custody"], prepared)
    count = integer(monitor["prefix_observations"], "receipt mounted prefix observations", 1)
    size = integer(monitor["prefix_bytes"], "receipt mounted prefix bytes", 1, len(raw))
    require(count == len(expected) - 3 and size == sum(len(encoded(row)) for row in rows[:count])
            and hashlib.sha256(raw[:size]).hexdigest() == monitor["prefix_sha256"],
            "receipt-authenticated exact mounted prefix differs")
    require(rows[-1]["owned_output_bytes"] >= receipt["terminal_owned_output_bytes"],
            "published mounted observation does not cover terminal charge")
    post_path = root / "postreceipt-disk-observations.jsonl"
    post_raw, post = read_rows(post_path, prepared["allocation"]["disk_upper_bytes"])
    require(post, "postreceipt mounted journal absent")
    post_custody = post[0]["initial_custody"]
    custody_checked(post_custody, contract)
    journal_checked(post, [("postreceipt-reservation", None, None), ("postreceipt-published", None, None)],
                    binding, post_custody, prepared)
    require(post_custody["snapshot"] == monitor["custody"]["snapshot"]
            and post[0]["begin_ns"] >= rows[-1]["end_ns"],
            "mounted custody/order changed between receipt and postreceipt publication")
    # Files added after publication are still charged: there is no namespace seal,
    # metadata exemption, evidence refund, or disk-to-RAM deduction.
    last = post[-1]
    charged = max(actual_bytes, receipt["terminal_owned_output_bytes"], last["owned_output_bytes"] + last["log_bytes"])
    disk_bounds(charged, last["internal_free_bytes"], last["external_free_bytes"],
                last["physical_backing_free_bytes"], 0, prepared)