#!/usr/bin/env python3
"""Pinned, read-only CPU storage inventory. Never constructs a neural model.

The original editor supplies the complete symbolic ZIP/pickle admission before
Torch is imported. This extension projects byte ranges, then checks every range
against the actual weights_only/CPU/mmap Tensor. The report contains no tensor
values and grants no numerical-control, native, or scientific authority.
"""
import ctypes
import gc
import hashlib
import importlib.metadata
import importlib.util
import io
import json
import math
import os
from pathlib import Path
import pickle
import pickletools
import re
import resource
import signal
import stat
import struct
import sys
import time
import zipfile
from collections import OrderedDict

SCHEMA = "omnius.nol.pytorch-control-reader-request.v1"
EDITOR_SHA = "aaee38b90eab4f0526610ad3ceea5e5be54890d1bdc49c57a2cf5d4fe3766570"
CODE = re.compile(r"(?:\.(?:py|pyi|pyd|dll|dylib|pth)|\.so(?:\.\d+)*)$|\.dist-info/(?:METADATA|WHEEL|entry_points\.txt)$")
LIMITS = {"maxInputBytes", "maxWorkingBytes", "maxReadBytes", "maxTensors", "maxCoordinates",
          "maxRuntimeBytes", "maxRuntimeFiles", "maxDurationMs", "maxProtocolBytes",
          "maxStderrBytes", "chunkBytes", "maxReportBytes", "maxAddressSpaceBytes"}


def need(ok, message):
    if not ok:
        raise ValueError(message)


def fields(value, required, optional=()):
    need(type(value) is dict and set(required) <= value.keys() <= set(required) | set(optional), "Unknown/missing reader fields")


def pairs(items):
    result = {}
    for key, value in items:
        need(key not in result, "Duplicate JSON key")
        result[key] = value
    return result


def parse(raw):
    return json.loads(raw, object_pairs_hook=pairs, parse_constant=lambda _: (_ for _ in ()).throw(ValueError("Nonfinite JSON")),
                      parse_int=lambda text: -0.0 if text == "-0" else int(text))


def encoded(value):
    return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()


def integer(value, minimum=0, maximum=9007199254740991):
    need(type(value) is int and minimum <= value <= maximum, "Invalid reader integer")
    return value


def regular(path):
    path = Path(path)
    info = path.lstat()
    need(stat.S_ISREG(info.st_mode) and not path.is_symlink() and path.resolve(strict=True) == path, "Reader source must be canonical nonsymlink regular file")
    return info


def identity(info):
    return (info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns)


class Budget:
    def __init__(self, limits):
        fields(limits, LIMITS)
        for value in limits.values():
            integer(value, 1)
        need(limits["maxProtocolBytes"] <= 16 * 1024 ** 2 and limits["maxStderrBytes"] <= 1024 ** 2 and
             4096 <= limits["chunkBytes"] <= 4 * 1024 ** 2 and limits["chunkBytes"] % 4 == 0 and
             limits["maxDurationMs"] <= 86400000, "Unsupported reader limits")
        self.limits, self.started = limits, time.monotonic()
        self.read_bytes = self.working = self.runtime_bytes = self.runtime_files = 0
        self.input = self.artifacts = self.arithmetic = 0
        self.stamps = {}
        self.directories = {}
        self.reserve(limits["chunkBytes"] * 3)

    def check(self):
        need(time.monotonic() - self.started <= self.limits["maxDurationMs"] / 1000, "Reader wall-clock budget exceeded")

    def read(self, count):
        self.check()
        self.read_bytes += integer(count)
        need(self.read_bytes <= self.limits["maxReadBytes"], "Reader logical-read byte budget exceeded")

    def reserve(self, count):
        self.check()
        self.working += integer(count)
        need(self.working <= self.limits["maxWorkingBytes"], "Reader working-byte budget exceeded")

    def guard(self):
        self.check()
        for path, stamp in self.stamps.items():
            need(identity(regular(path)) == stamp, "Reader source/runtime/checkpoint changed")
        for path, stamp in self.directories.items():
            info = Path(path).lstat()
            need(stat.S_ISDIR(info.st_mode) and not Path(path).is_symlink() and identity(info) == stamp, "Reader checkpoint directory inventory changed")


def hash_file(path, budget, maximum=None):
    path = Path(path)
    before = regular(path)
    need(maximum is None or before.st_size <= maximum, "Reader file exceeds declared bound")
    budget.read(before.st_size)
    result, size = hashlib.sha256(), 0
    with path.open("rb") as stream:
        need(identity(os.fstat(stream.fileno())) == identity(before), "Reader file changed while opening")
        while True:
            budget.check()
            block = stream.read(budget.limits["chunkBytes"])
            if not block:
                break
            size += len(block)
            need(size <= before.st_size, "Reader file grew")
            result.update(block)
        need(identity(os.fstat(stream.fileno())) == identity(before), "Reader file changed while hashing")
    need(size == before.st_size and identity(regular(path)) == identity(before), "Reader file extent/identity changed")
    budget.stamps[str(path)] = identity(before)
    return {"sha256": result.hexdigest(), "sizeBytes": size}


def read_range(path, offset, count, budget):
    info = regular(path)
    integer(offset)
    integer(count)
    need(offset + count <= info.st_size, "Reader range escaped actual source")
    budget.read(count)
    with Path(path).open("rb") as stream:
        need(identity(os.fstat(stream.fileno())) == identity(info), "Reader range source changed")
        stream.seek(offset)
        raw = stream.read(count)
        need(len(raw) == count and identity(os.fstat(stream.fileno())) == identity(info), "Reader range truncated/changed")
    return raw


def cpu_guard():
    need(all(os.environ.get(key) == "-1" for key in ("CUDA_VISIBLE_DEVICES", "HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES")), "Explicit denied CUDA/HIP/ROCR visibility required")
    need("torch" not in sys.modules and not any(name.startswith(("transformers", "llama_cpp", "gne")) for name in sys.modules), "Framework/model imported before CPU admission")
    need(sys.byteorder == "little", "Only little-endian CPU storage is supported")


def load_editor(payload, budget):
    cpu_guard()
    own = hash_file(Path(__file__).resolve(strict=True), budget)
    need(own["sha256"] == payload["expectedReaderSha256"], "Reader source pin mismatch")
    path = Path(payload["checkpointEditorPath"])
    source = hash_file(path, budget)
    need(source["sha256"] == payload["expectedCheckpointEditorSha256"] == EDITOR_SHA, "Exact symbolic-admission editor pin mismatch")
    spec = importlib.util.spec_from_file_location("nol_pinned_checkpoint_admission", path)
    need(spec is not None and spec.loader is not None, "Pinned editor import unavailable")
    editor = importlib.util.module_from_spec(spec)
    # This pinned module is stdlib-only at import. Never register it as a
    # substitutable package or execute its __main__ edit/publish entry point.
    spec.loader.exec_module(editor)
    cpu_guard()
    original = editor.hash_file

    def tracked_hash(path, original_budget=None):
        budget.read(regular(path).st_size)
        return original(path, original_budget)

    editor.hash_file = tracked_hash
    return editor, own, source


def runtime_inventory(payload, budget, own, editor_source):
    packages, names = [], set()
    for distribution in sorted(importlib.metadata.distributions(), key=lambda d: d.metadata.get("Name", "").lower()):
        budget.check()
        name = distribution.metadata.get("Name", "")
        if not name:
            continue
        need(name.lower() not in names, "Ambiguous duplicate installed distribution")
        names.add(name.lower())
        entries, total = [], 0
        for item in sorted(distribution.files or (), key=str):
            text = str(item)
            if not CODE.search(text) or "__pycache__" in text:
                continue
            path = Path(os.path.abspath(distribution.locate_file(item)))
            info = regular(path)
            budget.runtime_bytes += info.st_size
            budget.runtime_files += 1
            need(budget.runtime_bytes <= budget.limits["maxRuntimeBytes"] and budget.runtime_files <= budget.limits["maxRuntimeFiles"], "Reader runtime inventory budget exceeded")
            actual = hash_file(path, budget)
            total += actual["sizeBytes"]
            entries.append({"path": text, **actual})
        packages.append({"name": name, "version": distribution.version, "files": len(entries), "bytes": total,
                         "digest": hashlib.sha256(encoded(entries)).hexdigest()})
    need(any(p["name"].lower() == "torch" for p in packages), "Explicit CPU Torch reader environment unavailable")
    body = {"schema": "omnius.nol.pytorch-control-reader-runtime.v1", "pythonVersion": sys.version.split()[0],
            "pythonExecutable": hash_file(Path(sys.executable).resolve(strict=True), budget), "packages": packages,
            "reader": own, "checkpointEditor": editor_source,
            "dependencyLock": hash_file(Path(payload["dependencyLockPath"]), budget, 1024 ** 2)}
    cpu_guard()
    return {**body, "runtimeDigest": hashlib.sha256(encoded(body)).hexdigest()}


def central_admission(path, budget):
    """Bound ZIP metadata BEFORE ZipFile allocates its central-directory list."""
    size = regular(path).st_size
    need(size >= 22 and read_range(path, 0, 4, budget) == b"PK\x03\x04", "Legacy/non-ZIP or prefixed PyTorch checkpoint unsupported")
    start = max(0, size - 65557)
    tail = read_range(path, start, size - start, budget)
    end = tail.rfind(b"PK\x05\x06")
    need(end >= 0 and end + 22 <= len(tail), "Missing ZIP central-directory terminator")
    _, disk, central_disk, disk_entries, entries, central_bytes, central_offset, comment = struct.unpack_from("<4s4H2IH", tail, end)
    need(end + 22 + comment == len(tail) and disk == central_disk == 0 and entries == disk_entries, "Multidisk/trailing ZIP metadata unsupported")
    bound = start + end
    if entries == 65535 or central_bytes == 0xffffffff or central_offset == 0xffffffff:
        need(bound >= 20, "Missing ZIP64 locator")
        locator = read_range(path, bound - 20, 20, budget)
        signature, locator_disk, record_offset, disks = struct.unpack("<4sIQI", locator)
        need(signature == b"PK\x06\x07" and locator_disk == 0 and disks == 1, "Invalid ZIP64 locator")
        record = read_range(path, record_offset, 56, budget)
        signature, extent, _, _, disk, central_disk, disk_entries, entries, central_bytes, central_offset = struct.unpack("<4sQ2H2I4Q", record)
        need(signature == b"PK\x06\x06" and extent == 44 and disk == central_disk == 0 and entries == disk_entries, "Unsupported ZIP64 directory")
        bound = record_offset
    need(0 < entries <= budget.limits["maxTensors"] * 4 + 32 and central_bytes <= budget.limits["maxProtocolBytes"] and
         central_offset + central_bytes <= bound, "ZIP central-directory allocation/extent budget exceeded")
    budget.reserve(central_bytes * 8 + entries * 1024)


def project(path, editor, budget):
    # Complete original admission, unchanged and before Torch. The second
    # unpickler only projects ranges; actual Tensor objects verify it later.
    with zipfile.ZipFile(path) as precheck:
        records = precheck.infolist()
        need(all(entry.compress_type == zipfile.ZIP_STORED and not entry.flag_bits & 1 for entry in records), "Compressed/encrypted ZIP refused before pickle read")
        pickle_records = [entry for entry in records if entry.filename.endswith("/data.pkl")]
        need(len(pickle_records) == 1 and pickle_records[0].file_size <= budget.limits["maxProtocolBytes"], "Bounded single Tensor pickle required")
        raw = precheck.read(pickle_records[0])
        budget.read(len(raw))
        operations = 0
        for opcode, argument, _ in pickletools.genops(raw):
            operations += 1
            need(operations <= budget.limits["maxProtocolBytes"], "Pickle opcode work budget exceeded")
            if opcode.name in ("LONG_BINPUT", "BINPUT", "LONG_BINGET", "BINGET", "PUT", "GET"):
                need(0 <= int(argument) <= min(budget.limits["maxProtocolBytes"], budget.limits["maxTensors"] * 64 + 256), "Pickle memo allocation budget exceeded")
            if opcode.name == "FRAME":
                need(argument <= len(raw), "Pickle FRAME allocation exceeds actual metadata")
    editor.zip_admission(path, budget)
    with zipfile.ZipFile(path) as archive:
        entries = archive.infolist()
        pickle_entry = next(e for e in entries if e.filename.endswith("/data.pkl"))
        prefix = pickle_entry.filename[:-len("data.pkl")]
        need(prefix + "byteorder" in archive.namelist() and archive.read(prefix + "byteorder") == b"little", "Explicit little-endian ZIP byteorder required")
        storages = {e.filename[len(prefix + "data/"):]: e for e in entries if e.filename.startswith(prefix + "data/")}
        raw_pickle = archive.read(pickle_entry)
        budget.read(pickle_entry.file_size * 4)
        widths = {"FloatStorage": ("F32", 4), "HalfStorage": ("F16", 2), "BFloat16Storage": ("BF16", 2)}

        class Projection(pickle.Unpickler):
            def find_class(self, module, name):
                if module == "torch" and name in widths:
                    return widths[name]
                if module == "collections" and name == "OrderedDict":
                    return OrderedDict
                if module == "torch._utils" and name in ("_rebuild_tensor", "_rebuild_tensor_v2"):
                    return self.tensor
                raise ValueError("Unsupported PyTorch range-projection reducer/dtype")

            def persistent_load(self, value):
                need(type(value) is tuple and len(value) == 5 and value[0] == "storage" and type(value[1]) is tuple and
                     len(value[1]) == 2 and value[1] in widths.values() and type(value[2]) is str and value[2] in storages and
                     type(value[3]) is str and (value[3] == "cpu" or re.fullmatch(r"cuda:\d+", value[3])), "Unsupported typed storage device tag")
                count = integer(value[4])
                need(count * value[1][1] == storages[value[2]].file_size, "Projected storage extent mismatch")
                return {"key": value[2], "dtype": value[1][0], "width": value[1][1], "elements": count}

            @staticmethod
            def tensor(storage, offset, size, stride, requires_grad=False, hooks=None, metadata=None):
                need(type(storage) is dict and type(size) is tuple and type(stride) is tuple and len(size) == len(stride) <= 8 and
                     metadata in (None, {}) and not hooks, "Unsupported projected Tensor metadata")
                count, step = 1, 1
                for dimension in size:
                    count *= integer(dimension)
                    integer(count)
                for dimension, actual_stride in reversed(list(zip(size, stride))):
                    need(integer(actual_stride) == step or dimension <= 1, "Noncontiguous Tensor storage unsupported")
                    step *= max(1, dimension)
                need(integer(offset) == 0 and count == storage["elements"], "Narrowed/offset Tensor storage views unsupported")
                return {**storage, "shape": list(size), "stride": list(stride), "elements": count}

        stream = io.BytesIO(raw_pickle)
        result = Projection(stream).load()
        need(stream.tell() == len(raw_pickle) and isinstance(result, dict) and result and
             all(type(name) is str and name and "\0" not in name and type(item) is dict and "key" in item for name, item in result.items()), "Flat projected tensor-only state required")
        need(len(result) <= budget.limits["maxTensors"] and sum(t["elements"] for t in result.values()) <= budget.limits["maxCoordinates"], "Projected Tensor inventory/coordinate budget exceeded")
        need({t["key"] for t in result.values()} == set(storages), "Unreferenced/missing physical storage")
        by_storage = {}
        for item in result.values():
            by_storage.setdefault(item["key"], []).append(item)
        offsets = sorted(entry.header_offset for entry in entries)
        next_offsets = dict(zip(offsets, offsets[1:] + [archive.start_dir]))
        for key, entry in storages.items():
            header = read_range(path, entry.header_offset, 30, budget)
            signature, _, flags, compression, _, _, _, _, _, name_size, extra_size = struct.unpack("<4s5H3I2H", header)
            need(signature == b"PK\x03\x04" and flags == entry.flag_bits and not flags & 1 and compression == zipfile.ZIP_STORED, "ZIP local/central header mismatch")
            raw_name = read_range(path, entry.header_offset + 30, name_size, budget)
            need(raw_name.decode("utf-8" if flags & 0x800 else "cp437") == entry.filename, "ZIP local storage filename mismatch")
            first = entry.header_offset + 30 + name_size + extra_size
            next_header = next_offsets[entry.header_offset]
            need(first + entry.file_size <= next_header, "Overlapping ZIP storage data range")
            for item in by_storage[key]:
                item["dataOffsetBytes"] = first
                item["sizeBytes"] = entry.file_size
        return result


def inventory(payload, editor, runtime, budget):
    model, root = payload["model"], Path(payload["checkpointRoot"])
    need(root.is_absolute() and root.resolve(strict=True) == root and not root.is_symlink(), "Canonical checkpoint root required")
    need(model.get("format") in ("pytorch", "hf") and model.get("quantization", {}).get("method") == "none", "Only unquantized PyTorch checkpoints supported")
    total = sum(integer(f["artifact"]["sizeBytes"]) for f in model["files"])
    need(total <= budget.limits["maxInputBytes"], "Reader aggregate model input cap exceeded")
    expected = {file["path"] for file in model["files"]}
    need(len(expected) == len(model["files"]), "Duplicate checkpoint path")
    directories, actual = [root], set()
    while directories:
        directory = directories.pop()
        budget.check()
        info = directory.lstat()
        need(stat.S_ISDIR(info.st_mode) and not directory.is_symlink(), "Checkpoint directory symlink unsupported")
        budget.directories[str(directory)] = identity(info)
        need(len(budget.directories) <= len(expected) * 2 + 32, "Checkpoint directory work bound exceeded")
        with os.scandir(directory) as entries:
            for entry in entries:
                budget.check()
                need(not entry.is_symlink(), "Checkpoint symlink unsupported")
                path = Path(entry.path)
                if entry.is_dir(follow_symlinks=False):
                    directories.append(path)
                else:
                    name = path.relative_to(root).as_posix()
                    need(entry.is_file(follow_symlinks=False) and name in expected, "Unmanifested/nonregular checkpoint source")
                    actual.add(name)
                    need(len(actual) <= len(expected), "Checkpoint inventory bound exceeded")
    need(actual == expected, "Missing complete checkpoint inventory")
    projections = {}
    for file in model["files"]:
        actual = hash_file(editor.safe(root, file["path"]), budget)
        need(actual == {"sha256": file["artifact"]["sha256"], "sizeBytes": file["artifact"]["sizeBytes"]}, "Complete frozen checkpoint hash mismatch before metadata admission")
        if file["role"] == "weights":
            path = editor.safe(root, file["path"])
            central_admission(path, budget)
    # Project/admit before Checkpoint's repeated original guard as well; the
    # extra memo/frame bound protects the stdlib unpickler's own allocation.
    for file in model["files"]:
        if file["role"] == "weights":
            need(file["path"].endswith((".bin", ".pt", ".pth")), "Mixed/safetensors physical codec unsupported by PyTorch reader")
            projections[file["path"]] = project(editor.safe(root, file["path"]), editor, budget)
    checkpoint = editor.Checkpoint(model, root, payload["identity"], budget)
    need(checkpoint.kind == "torch", "Mixed/safetensors physical codec unsupported by PyTorch reader")
    need(sum(len(items) for items in projections.values()) <= budget.limits["maxTensors"], "Aggregate Tensor inventory cap exceeded")
    need(sum(item["elements"] for items in projections.values() for item in items.values()) <= budget.limits["maxCoordinates"], "Aggregate Tensor coordinate cap exceeded")
    names = [name for items in projections.values() for name in items]
    need(len(set(names)) == len(names), "Duplicate projected Tensor across shards")
    # All complete model bytes, ZIP/pickle metadata, resource bounds and the
    # full pinned runtime must be admitted BEFORE the first Torch import.
    actual_runtime = runtime()
    need(editor.same(actual_runtime, payload["runtime"]), "Pinned reader runtime changed")
    cpu_guard()
    import torch
    need(torch.cuda.is_initialized() is False, "CPU reader unexpectedly initialized CUDA")
    torch.set_num_threads(1)
    # Conservative native mmap/metadata read allowance, not a claim about
    # physical disk IO or page-cache traffic. Explicit hash/range/memory reads
    # are separately charged below.
    budget.read(total * 2)
    checkpoint.load_torch(torch)
    tensors, aliases, seen = [], {}, set()
    dtype_names = {torch.float32: "F32", torch.float16: "F16", torch.bfloat16: "BF16"}
    for source, items in projections.items():
        state = checkpoint.states[source]
        need(set(state) == set(items), "Actual Tensor inventory differs from symbolic projection")
        for name, projected in items.items():
            budget.check()
            need(name not in seen, "Duplicate Tensor across shards")
            seen.add(name)
            tensor = state[name]
            need(type(tensor) is torch.Tensor and tensor.device.type == "cpu" and tensor.layout == torch.strided and
                 tensor.is_contiguous() and not tensor.is_quantized and tensor.dtype in dtype_names, "Unsupported actual Tensor dtype/layout/device")
            need(dtype_names[tensor.dtype] == projected["dtype"] and list(tensor.shape) == projected["shape"] and list(tensor.stride()) == projected["stride"] and
                 tensor.storage_offset() == 0 and tensor.numel() * tensor.element_size() == tensor.untyped_storage().nbytes() == projected["sizeBytes"], "Actual Tensor metadata/storage differs from projection")
            size, sha, path = projected["sizeBytes"], hashlib.sha256(), editor.safe(root, source)
            for offset in range(0, size, budget.limits["chunkBytes"]):
                budget.check()
                count = min(budget.limits["chunkBytes"], size - offset)
                budget.read(count)
                memory = ctypes.string_at(tensor.data_ptr() + offset, count)
                actual = read_range(path, projected["dataOffsetBytes"] + offset, count, budget)
                need(memory == actual, "Actual mmap Tensor bits differ from frozen source storage range")
                sha.update(memory)
            group = source + ":" + projected["key"]
            aliases.setdefault(group, []).append(name)
            tensors.append({"name": name, "dtype": projected["dtype"], "shape": projected["shape"], "sourceFile": source,
                            "storageKey": projected["key"], "dataOffsetBytes": projected["dataOffsetBytes"], "sizeBytes": size,
                            "sha256": sha.hexdigest(), "elements": projected["elements"], "aliasGroup": group})
    need(not torch.cuda.is_initialized(), "CPU Tensor read unexpectedly initialized CUDA")
    files = []
    for file in model["files"]:
        path = editor.safe(root, file["path"])
        actual = hash_file(path, budget)
        need(actual == {"sha256": file["artifact"]["sha256"], "sizeBytes": file["artifact"]["sizeBytes"]}, "Checkpoint changed after mmap verification")
        files.append({"path": file["path"], "role": file["role"], **actual})
    checkpoint.states.clear()
    del tensor
    gc.collect()
    budget.guard()
    return {"schema": "omnius.nol.pytorch-control-inventory.v1", "modelDigest": model["modelDigest"],
            "runtimeDigest": actual_runtime["runtimeDigest"], "readerSha256": actual_runtime["reader"]["sha256"],
            "checkpointEditorSha256": EDITOR_SHA, "files": files, "tensors": sorted(tensors, key=lambda t: t["name"]),
            "aliases": [{"id": key, "tensors": sorted(names)} for key, names in sorted(aliases.items()) if len(names) > 1],
            "usage": {"inputBytes": total, "logicalReadBytes": budget.read_bytes, "reservedWorkingBytes": budget.working},
            "symbolicAdmissionBeforeTorch": True, "weightsOnly": True, "mmap": True, "device": "cpu",
            "cudaInitialized": False, "modelConstructed": False, "numericalControlVerified": False, "authority": "none"}


def main():
    raw = sys.stdin.buffer.read(16 * 1024 ** 2 + 1)
    need(len(raw) <= 16 * 1024 ** 2, "Absolute reader request cap exceeded")
    payload = parse(raw)
    fields(payload, ("schema", "action", "expectedReaderSha256", "checkpointEditorPath", "expectedCheckpointEditorSha256", "dependencyLockPath", "limits"),
           ("runtime", "model", "checkpointRoot", "identity"))
    need(payload["schema"] == SCHEMA and payload["action"] in ("inspect", "inventory"), "Unsupported reader action/schema")
    budget = Budget(payload["limits"])
    need(len(raw) <= budget.limits["maxProtocolBytes"], "Reader request protocol cap exceeded")
    resource.setrlimit(resource.RLIMIT_AS, (budget.limits["maxAddressSpaceBytes"], budget.limits["maxAddressSpaceBytes"]))
    resource.setrlimit(resource.RLIMIT_CPU, (max(1, math.ceil(budget.limits["maxDurationMs"] / 1000)), max(2, math.ceil(budget.limits["maxDurationMs"] / 1000) + 1)))
    editor, own, source = load_editor(payload, budget)
    runtime = lambda: runtime_inventory(payload, budget, own, source)
    if payload["action"] == "inspect":
        need(not any(key in payload for key in ("runtime", "model", "checkpointRoot", "identity")), "Inspect does not accept checkpoint/model input")
        result = {"runtime": runtime(), "torchImported": False, "cudaInitialized": False, "modelConstructed": False}
        budget.guard()
    else:
        need(all(key in payload for key in ("runtime", "model", "checkpointRoot", "identity")), "Frozen runtime/model input required")
        result = inventory(payload, editor, runtime, budget)
    raw = encoded(result)
    need(len(raw) <= budget.limits["maxProtocolBytes"], "Reader response protocol cap exceeded")
    sys.stdout.buffer.write(raw)
    sys.stdout.flush()


if __name__ == "__main__":
    try:
        signal.signal(signal.SIGTERM, lambda *_: (_ for _ in ()).throw(InterruptedError("CPU reader Stop")))
        main()
    except BaseException as error:
        sys.stderr.write((type(error).__name__ + ": " + str(error))[-4000:] + "; torchImported=" + str("torch" in sys.modules).lower() + "\n")
        sys.exit(1)
