#!/usr/bin/env python3
"""Bounded data-only vLLM request runtime. Importing this module is stdlib-only.

The actual engine/tokenizer/hooks are trusted host ports, never request Python.
No model constructor is enabled here. Native activation is still gated by the
adjacent owned worker's source-owned designation and private placement channel.
CPU fixture ports establish orchestration only, never native conformance.
"""
import hashlib
import contextlib
import sys
import json
import math
import re
import time

VERSION = "omnius.nol.vllm-runtime.v1"
SHA = re.compile(r"^[a-f0-9]{64}$")
UINT = 4294967295
DECODE = {"detokenize": True, "skip_special_tokens": True, "spaces_between_special_tokens": True,
          "include_stop_str_in_output": False, "ignore_eos": False, "stop": [], "stop_token_ids": [], "n": 1}


class Rejected(RuntimeError):
    def __init__(self, message, code="INVALID", fatal=True):
        super().__init__(message)
        self.code, self.fatal = code, fatal


def require(value, message, code="INVALID"):
    if not value: raise Rejected(message, code)


def fields(value, required, optional=()):
    require(type(value) is dict and set(required) <= set(value) and set(value) <= set(required) | set(optional), "Unknown/missing runtime fields")


def integer(value, low, high):
    require(type(value) is int and low <= value <= high, "Runtime integer bound exceeded", "CAPACITY")
    return value


def finite(value, low, high):
    require(type(value) in (int, float) and math.isfinite(value) and low <= value <= high, "Runtime finite bound exceeded", "CAPACITY")
    return value


def lease_gpu_memory_utilization(reserved_mib, total_device_bytes):
    """vLLM's initial ceil(total*fraction) promise must fit this exact lease."""
    budget = integer(reserved_mib, 1024, 131072) * 1048576
    total = integer(total_device_bytes, 1, 128 * 1073741824)
    fraction = min(1.0, budget / total)
    if math.ceil(total * fraction) > budget:
        fraction = math.nextafter(fraction, 0.0)
    require(0 < fraction <= 1 and 0 < math.ceil(total * fraction) <= budget,
            "Initial GPU memory request exceeds the exact lease budget", "CAPACITY")
    return fraction


def verify_lease_gpu_memory_utilization(cache_config, expected):
    actual = cache_config.gpu_memory_utilization
    require(type(actual) in (int, float) and math.isfinite(actual) and actual == expected,
            "Native GPU memory utilization differs from the exact lease-derived value", "IDENTITY")


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


def clone(value): return json.loads(canonical(value))
def sha(value): return hashlib.sha256(value).hexdigest()


def parse_json(raw):
    def pairs(items):
        result = {}
        for key, value in items:
            require(key not in result, "Duplicate runtime JSON key")
            result[key] = value
        return result
    value = json.loads(raw, object_pairs_hook=pairs, parse_constant=lambda _: (_ for _ in ()).throw(Rejected("Nonfinite runtime JSON")))
    canonical(value)
    return value


def artifact(value):
    fields(value, ("uri", "sha256", "sizeBytes", "mediaType"))
    require(type(value["sha256"]) is str and SHA.fullmatch(value["sha256"]) and value["uri"] == "omnius-artifact://sha256/" + value["sha256"], "Full runtime source artifact required", "IDENTITY")
    integer(value["sizeBytes"], 0, 1048576)
    require(type(value["mediaType"]) is str and len(value["mediaType"]) <= 200, "Bounded prompt media type required")
    return value


def parse_prompt(value, maximum):
    fields(value, ("prompt", "promptArtifact"))
    require(type(value["prompt"]) is str, "Exact UTF8 prompt source required")
    raw = value["prompt"].encode("utf-8")
    require(len(raw) <= maximum, "Prompt byte bound exceeded", "CAPACITY")
    ref = artifact(value["promptArtifact"])
    require(ref["sha256"] == sha(raw) and ref["sizeBytes"] == len(raw), "Actual prompt source bytes differ", "IDENTITY")
    if ref["mediaType"].split(";", 1)[0] == "text/plain": messages = [{"role": "user", "content": value["prompt"]}]
    else:
        require(ref["mediaType"] == "application/json", "Unsupported prompt media type", "UNSUPPORTED")
        document = parse_json(value["prompt"])
        fields(document, ("schema", "messages"))
        require(document["schema"] == "omnius.nol.chat-input.v1", "Unknown chat prompt schema")
        messages = document["messages"]
    require(type(messages) is list and 1 <= len(messages) <= 64, "Bounded plain chat messages required")
    for i, message in enumerate(messages):
        fields(message, ("role", "content"))
        require(message["role"] in ("system", "user", "assistant") and type(message["content"]) is str, "Plain chat only", "UNSUPPORTED")
        require(message["role"] != "system" or i == 0, "Only an initial system message is supported", "UNSUPPORTED")
    return clone(messages), clone(ref)


def token_ids(values, maximum):
    require(type(values) is list and 1 <= len(values) <= maximum, "Bounded nonempty native token IDs required", "CAPACITY")
    for value in values: integer(value, 0, UINT)
    return list(values)


def parse_operations(recipe, identity_json, binding, sites):
    if recipe is None:
        require(identity_json is None, "Null recipe has unexpected identity")
        return []
    fields(recipe, ("schema", "id", "revision", "recipeDigest", "modelDigest", "architectureMapDigest", "parentModelDigests", "operations", "calibrations", "createdAt", "provenance"), ("approximateLoweringAcknowledged",))
    require(recipe["schema"] == "omnius.nol.recipe.v1" and recipe["modelDigest"] == binding["modelDigest"] and recipe["architectureMapDigest"] == binding["architectureMapDigest"], "Exact runtime recipe binding required", "IDENTITY")
    require(type(identity_json) is str and len(identity_json.encode()) <= 131072 and SHA.fullmatch(recipe["recipeDigest"] or ""), "Bounded exact recipe identity required", "IDENTITY")
    body = {key: value for key, value in recipe.items() if key != "recipeDigest"}
    require(parse_json(identity_json) == body and sha(identity_json.encode()) == recipe["recipeDigest"], "Recipe identity bytes differ", "IDENTITY")
    require(recipe["calibrations"] == [] and "approximateLoweringAcknowledged" not in recipe, "Raw verified activation operations only", "UNSUPPORTED")
    operations = recipe["operations"]
    require(type(operations) is list and 1 <= len(operations) <= 2, "One operation or two sparse ADD coordinates supported", "UNSUPPORTED")
    seen, ids = set(), set()
    for op in operations:
        require(type(op) is dict and op.get("operation") in ("NEURON_ADD", "NEURON_GAIN"), "Unsupported runtime operation", "UNSUPPORTED")
        fields(op, ("id", "siteId", "operation", "tokenScope", "neuron", "amount", "units") if op["operation"] == "NEURON_ADD" else ("id", "siteId", "operation", "tokenScope", "neuron", "factor"))
        site = sites.get(op["siteId"])
        require(site and site["kind"] == "mlp_intermediate" and site["width"] == 9216 and 0 <= site["layer"] < 32, "Unverified dense runtime site", "UNSUPPORTED")
        require(type(op["id"]) is str and 0 < len(op["id"]) <= 160 and op["id"] not in ids, "Distinct operation identity required")
        ids.add(op["id"])
        integer(op["neuron"], 0, site["width"] - 1)
        require(op["tokenScope"] == {"kind": "all"}, "Only all valid computation positions are supported", "UNSUPPORTED")
        if op["operation"] == "NEURON_ADD":
            require(op["units"] == "raw", "No hidden activation calibration", "UNSUPPORTED")
            finite(op["amount"], -16, 16)
        else: finite(op["factor"], 0, 4)
        coordinate = (op["siteId"], op["neuron"])
        require(coordinate not in seen, "Overlapping operation order is unverified", "UNSUPPORTED")
        seen.add(coordinate)
    if len(operations) == 2:
        require(all(op["operation"] == "NEURON_ADD" and op["siteId"] == operations[0]["siteId"] for op in operations), "Two-operation support is same-site sparse ADD only", "UNSUPPORTED")
    return clone(operations)


def request_performance(metrics, engine_wall_seconds, actual_tokens, stats_enabled, memory=None):
    """Pinned vLLM RequestStateStats facts, never a wall-time phase guess.
    Arrival is frontend wall-clock; core event timestamps are monotonic. Do not
    subtract across them. Default zero timestamps are unavailable observations.
    """
    finite(engine_wall_seconds, 0, 7200)
    require(type(stats_enabled) is bool, "Native statistics mode missing", "IDENTITY")
    facts = None
    if metrics is not None:
        facts = {}
        for key in ("arrival_time", "queued_ts", "scheduled_ts", "first_token_ts", "last_token_ts", "first_token_latency"):
            value = getattr(metrics, key, None)
            finite(value, 0, 1e12)
            facts[key] = value
        count = integer(getattr(metrics, "num_generation_tokens", None), 0, 256)
        require(count in (0, actual_tokens), "Native metrics token count differs from actual engine output", "IDENTITY")
        facts["num_generation_tokens"] = count
        require(getattr(metrics, "is_corrupted", False) is False, "Native metrics report corrupted logits", "IDENTITY")
        facts["is_corrupted"] = False
        finite(facts["first_token_latency"], 0, 7200)
    def interval(start, end):
        if facts is None or facts[start] == 0 or facts[end] == 0: return None
        value = facts[end] - facts[start]
        finite(value, 0, 7200)
        return value
    return {"schema": "omnius.nol.vllm-performance.v1", "statsEnabled": stats_enabled,
            "facts": facts, "arrivalClock": "frontend_wall_time_seconds", "eventClock": "engine_core_monotonic_seconds",
            "queueSeconds": interval("queued_ts", "scheduled_ts"),
            "prefillSeconds": interval("scheduled_ts", "first_token_ts"),
            "decodeSeconds": interval("first_token_ts", "last_token_ts"),
            "ttftSeconds": None if facts is None or facts["first_token_latency"] == 0 else facts["first_token_latency"],
            "engineWallSeconds": engine_wall_seconds,
            "engineWallDefinition": "monotonic_add_request_through_final_synchronous_step_including_observers_excluding_decoder_replay_and_reset",
            "nativePhaseDefinition": "vllm_0.27.1_request_state_stats_prefill_and_decode_include_preemptions",
            "missingTimestampMeaning": "none_or_zero_native_timestamp_is_unavailable_not_zero_latency",
            "memory": memory, "memoryUnavailableReason": "native_cuda_allocator_snapshot_unavailable" if memory is None else None}


class Runtime:
    """One engine, one request at a time; actual native ports are host-only.

    bridge exposes ONLY arm/clear/status. It is not a generic RPC or trace API.
    authorize_operations must synchronously assert authentic conformance and
    return None, never accept a serialized success boolean.
    """
    def __init__(self, *, engine, tokenizer, sampling_params, replay_decoder, bridge, authorize_operations, binding, source, sites, limits, now=time.monotonic):
        self.engine, self.tokenizer, self.sampling_params, self.replay_decoder = engine, tokenizer, sampling_params, replay_decoder
        self.bridge, self.authorize_operations = bridge, authorize_operations
        self.binding, self.sites, self.limits, self.now = clone(binding), clone(sites), clone(limits), now
        fields(source, ("workerSha256", "companionSha256", "runtimeSha256"))
        require(all(type(v) is str and SHA.fullmatch(v) for v in source.values()), "Full runtime source pins required", "IDENTITY")
        self.source = clone(source)
        fields(limits, ("maxPromptBytes", "maxInputTokens", "maxOutputTokens", "maxOutputBytes", "maxEngineSteps", "maxWallTimeMs", "maxRequests", "maxForwardPositions"))
        for key, cap in (("maxPromptBytes", 1048576), ("maxInputTokens", 256), ("maxOutputTokens", 256), ("maxOutputBytes", 1048576), ("maxEngineSteps", 512), ("maxWallTimeMs", 7200000), ("maxRequests", 1000), ("maxForwardPositions", 512)):
            integer(limits[key], 1, cap)
        require(binding.get("backend") == "vllm" and all(SHA.fullmatch(binding.get(key, "")) for key in ("modelDigest", "architectureMapDigest", "runtimeBuildDigest", "tokenizerDigest", "chatTemplateDigest", "dependencyLockDigest")), "Full vLLM binding required", "IDENTITY")
        integer(binding["contextLimit"], 1, 256)
        require(all(callable(x) for x in (sampling_params, replay_decoder, authorize_operations)), "Trusted runtime ports required")
        self.epoch, self.requests, self.used = 0, 0, set()
        self.tokenized, self.last_reset, self.failure = None, None, None
        self.active, self.poisoned = None, False

    def _idle(self):
        require(not self.poisoned and self.active is None, "Runtime has active/failed custody", "CUSTODY")
        require(not self.engine.has_unfinished_requests(), "Engine requests remain outstanding", "CUSTODY")
        status = self.bridge.status()
        require(status.get("activeRequestId") is None and status.get("hooks") == 0 and status.get("observerHooks") == 0 and status.get("nnsightRequests") == 0 and status.get("registeredBlocks") == 0, "Native hooks/mediators remain outstanding", "CUSTODY")
        return status

    def tokenize(self, payload):
        self._idle()
        require(self.engine.get_tokenizer() is self.tokenizer, "Engine tokenizer identity changed", "IDENTITY")
        messages, ref = parse_prompt(payload, self.limits["maxPromptBytes"])
        rendered = self.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True, enable_thinking=False)
        require(type(rendered) is str and len(rendered.encode()) <= self.limits["maxPromptBytes"], "Rendered prompt exceeds bound", "CAPACITY")
        ids = token_ids(self.tokenizer.encode(rendered, add_special_tokens=False), self.limits["maxInputTokens"])
        same_ids = token_ids(self.tokenizer.apply_chat_template(messages, tokenize=True, return_dict=False, add_generation_prompt=True, enable_thinking=False), self.limits["maxInputTokens"])
        require(ids == same_ids, "Actual tokenizer template/encode paths disagree", "IDENTITY")
        result = {"schema": "omnius.nol.vllm-tokenization.v1", "binding": clone(self.binding), "promptArtifact": ref, "renderedPrompt": rendered, "renderedSha256": sha(rendered.encode()), "renderedBytes": len(rendered.encode()), "tokenIds": ids, "promptTokens": len(ids), "thinking": False}
        self.tokenized = clone(result)
        return result

    def reset(self):
        self._idle()
        self.bridge.clear()
        require(self.engine.reset_prefix_cache(reset_running_requests=False, reset_connector=False) is True, "Idle prefix-cache reset failed", "CUSTODY")
        self._idle(); self.epoch += 1
        self.last_reset = {"schema": "omnius.nol.vllm-reset.v1", "binding": clone(self.binding), "epoch": self.epoch, "hooks": 0, "activeRequests": 0, "nnsightRequests": 0, "prefixCaching": False, "cacheScope": "logical_fresh_request_identity", "rawKvErasureClaim": False}
        return clone(self.last_reset)

    def _engine_request_id(self, request_id, prompt_ids, returned=None):
        processor = self.engine.output_processor
        states, mapping = processor.request_states, processor.external_req_ids
        require(type(states) is dict and isinstance(mapping, dict) and set(mapping) == {request_id},
                "Exact sole external request mapping unavailable", "CUSTODY")
        internal_ids = mapping[request_id]
        require(type(internal_ids) is list and len(internal_ids) == 1 and type(internal_ids[0]) is str and
                re.fullmatch(re.escape(request_id) + r"-[0-9a-f]{8}", internal_ids[0]) is not None,
                "Actual engine internal request identity differs", "IDENTITY")
        internal = internal_ids[0]
        require(set(states) == {internal} and states[internal].external_req_id == request_id and
                states[internal].prompt_token_ids == prompt_ids,
                "Exact internal request mapping/prompt differs", "IDENTITY")
        require(returned is None or returned == internal, "Engine returned internal request ID differs from official mapping", "IDENTITY")
        return internal

    def _cleanup(self, request_id, prompt_ids, internal_id=None):
        # reset_prefix_cache(True) PREEMPTS/REQUEUES: it is never cancellation.
        # A partial add can register before throwing; recover only its exact
        # sole official mapping, never another request or an inferred ID.
        if self.engine.has_unfinished_requests():
            actual = self._engine_request_id(request_id, prompt_ids, internal_id)
            self.engine.abort_request([actual], internal=True)
        self.bridge.clear()
        require(not self.engine.has_unfinished_requests(), "Abort left native engine requests outstanding", "CUSTODY")
        status = self.bridge.status()
        require(status.get("activeRequestId") is None and status.get("hooks") == 0 and status.get("observerHooks") == 0 and status.get("nnsightRequests") == 0 and status.get("registeredBlocks") == 0, "Abort left native intervention/mediator custody", "CUSTODY")
        return status

    def generate(self, payload):
        self._idle()
        fields(payload, ("prompt", "promptArtifact", "recipe", "recipeIdentityJson", "cacheKeyDigest", "seed", "maxTokens", "decoding"))
        key = payload["cacheKeyDigest"]
        require(type(key) is str and SHA.fullmatch(key) and key not in self.used and self.requests < self.limits["maxRequests"], "Request identity replay/allowance", "CUSTODY")
        integer(payload["seed"], 0, UINT); integer(payload["maxTokens"], 1, self.limits["maxOutputTokens"])
        fields(payload["decoding"], ("temperature", "topP", "topK", "constrainedDecoding"))
        decoding = payload["decoding"]
        finite(decoding["temperature"], 0, 2); finite(decoding["topP"], 0.000001, 1); integer(decoding["topK"], 0, 1000000)
        require(decoding["constrainedDecoding"] == "none", "Constrained generation needs separate conformance", "UNSUPPORTED")
        require(self.last_reset is not None and self.tokenized is not None, "Explicit one-use tokenize/reset required", "CUSTODY")
        _, ref = parse_prompt({key: payload[key] for key in ("prompt", "promptArtifact")}, self.limits["maxPromptBytes"])
        require(ref == self.tokenized["promptArtifact"], "Generation source differs from exact token admission", "IDENTITY")
        admitted = clone(self.tokenized)
        ids = list(admitted["tokenIds"])
        require(len(ids) + payload["maxTokens"] <= self.binding["contextLimit"] and len(ids) + payload["maxTokens"] - 1 <= self.limits["maxForwardPositions"], "Generation context/position bound exceeded", "CAPACITY")
        operations = parse_operations(payload["recipe"], payload["recipeIdentityJson"], self.binding, self.sites)
        require(self.authorize_operations(clone(operations), None if payload["recipe"] is None else payload["recipe"]["recipeDigest"]) is None, "Conformance authority must assert, not return a passed flag", "CUSTODY")
        before, self.last_reset = self.last_reset, None
        self.used.add(key); self.requests += 1; self.active = key
        self.failure = {"requestId": key, "dispatchReserved": True, "promptTokens": len(ids), "completionUpperBound": payload["maxTokens"], "knownCompletionTokens": 0, "usageComplete": False}
        started, steps, finished, native_status = self.now(), 0, None, None
        engine_request_id = None
        try:
            params = self.sampling_params({**clone(DECODE), "seed": payload["seed"], "temperature": decoding["temperature"], "top_p": decoding["topP"], "top_k": -1 if decoding["topK"] == 0 else decoding["topK"], "max_tokens": payload["maxTokens"], "min_tokens": 0})
            self.bridge.arm({"requestId": key, "operations": operations, "promptTokenIds": ids, "maxTokens": payload["maxTokens"], "maxForwardPositions": self.limits["maxForwardPositions"]})
            engine_started = self.now()
            returned_id = self.engine.add_request(key, {"prompt_token_ids": list(ids)}, params)
            require(type(returned_id) is str, "Engine add_request did not return an internal request ID", "IDENTITY")
            engine_request_id = self._engine_request_id(key, ids, returned_id)
            self.failure["engineRequestId"] = engine_request_id
            self.bridge.bind_engine_request(key, engine_request_id)
            while self.engine.has_unfinished_requests():
                require(steps < self.limits["maxEngineSteps"] and (self.now() - started) * 1000 <= self.limits["maxWallTimeMs"], "Bounded engine step/deadline exhausted", "CAPACITY")
                outputs = self.engine.step(); steps += 1
                require((self.now() - started) * 1000 <= self.limits["maxWallTimeMs"], "Actual engine step exceeded request wall budget", "CAPACITY")
                require(type(outputs) is list and len(outputs) <= 1, "Unexpected engine batch", "CUSTODY")
                for result in outputs:
                    require(result.request_id == key and result.prompt_token_ids == ids and len(result.outputs) == 1, "Native request/prompt/sequence identity differs", "IDENTITY")
                    completion = result.outputs[0]
                    tokens = list(completion.token_ids)
                    if tokens or result.finished: token_ids(tokens, payload["maxTokens"])
                    self.failure["knownCompletionTokens"] = max(self.failure["knownCompletionTokens"], len(tokens))
                    require(getattr(result, "num_cached_tokens", 0) in (None, 0), "Unexpected prefix-cache hit", "CUSTODY")
                    if result.finished:
                        require(finished is None and completion.finish_reason in ("stop", "length") and getattr(result, "nnsight_error", None) is None, "Native completion/error differs", "CUSTODY")
                        finished = result
            require(finished is not None, "Engine became idle without a final output", "CUSTODY")
            completion = finished.outputs[0]; tokens = list(completion.token_ids)
            memory = self.bridge.memory_observation() if callable(getattr(self.bridge, "memory_observation", None)) else None
            performance = request_performance(getattr(finished, "metrics", None), self.now() - engine_started, len(tokens), bool(getattr(self.engine, "log_stats", True)), memory)
            require(type(completion.text) is str and len(completion.text.encode()) <= self.limits["maxOutputBytes"], "Native text bound exceeded", "CAPACITY")
            require(completion.stop_reason is None or type(completion.stop_reason) is int and 0 <= completion.stop_reason <= UINT, "Unexpected native stop reason", "IDENTITY")
            require(completion.finish_reason != "length" or len(tokens) == payload["maxTokens"], "Native length termination differs from frozen sampling cap", "IDENTITY")
            replay = self.replay_decoder(list(ids), list(tokens), completion.finish_reason, params)
            require(type(replay) is dict and replay.get("text") == completion.text and replay.get("tokenIds") == tokens and SHA.fullmatch(replay.get("implementationSha256", "")), "Independent pinned incremental decoder differs", "IDENTITY")
            native_status = clone(self.bridge.status())
            require(native_status.get("requestId") == key and native_status.get("engineRequestId") == engine_request_id and native_status.get("operations") == operations and native_status.get("witnesses") == native_status.get("hookCalls") and native_status.get("forwardPositions", UINT) <= self.limits["maxForwardPositions"], "Actual native hook/witness accounting differs", "CUSTODY")
            require(native_status.get("forwardPositions") == len(ids) + len(tokens) - 1 and native_status.get("forwards") == len(tokens) and native_status.get("sampledTokens") == len(tokens) and native_status.get("positions") == list(range(len(ids) + len(tokens) - 1)), "Native scheduled positions/sample rows differ from actual request", "CUSTODY")
            require(native_status.get("sampledTokenIds") == tokens and native_status.get("activeRequestId") in (None, key) and native_status.get("hooks") == (2 if operations else 0) and native_status.get("hookCalls") == (len(tokens) if operations else 0), "Native site hook topology/count differs", "CUSTODY")
            self._cleanup(key, ids, engine_request_id); self.active = None
            after = self.reset()
            self.tokenized, self.last_reset = None, None
            self.failure = None
            return {"text": completion.text, "promptTokenIds": list(ids), "tokenIds": tokens, "usage": {"promptTokens": len(ids), "completionTokens": len(tokens)}, "finishReason": completion.finish_reason, "stopReason": completion.stop_reason,
                    "native": {"binding": clone(self.binding), "source": clone(self.source), "sourcePromptArtifact": ref, "renderedSha256": admitted["renderedSha256"], "implementation": VERSION, "requestId": key, "engineRequestId": engine_request_id, "cacheKeyDigest": key, "recipeDigest": None if payload["recipe"] is None else payload["recipe"]["recipeDigest"], "operations": operations, "resetBefore": before, "resetAfter": after, "usesCache": True, "cacheScope": "within_request_only_prefix_disabled", "rawKvErasureClaim": False, "decoder": {"kind": "pinned_incremental_replay", "implementationSha256": replay["implementationSha256"], "parameters": clone(DECODE), "textSha256": sha(completion.text.encode()), "utf8Bytes": len(completion.text.encode())}, "performance": performance, "work": native_status, "engineSteps": steps, "nativeConformance": "unverified", "capabilityAuthority": "none"}}
        except BaseException as primary:
            try:
                self._cleanup(key, ids, engine_request_id)
            except BaseException as cleanup_error:
                raise cleanup_error from primary
            finally:
                self.active = None; self.poisoned = True
            raise


def make_native_decoder_replay(tokenizer):
    """Lazy framework import, used only after designated native engine load.
    A new pinned decoder is primed with actual prompt IDs; final STOP IDs remain
    in token accounting even when the engine deliberately omits them from text.
    """
    from types import SimpleNamespace
    from vllm.v1.engine.detokenizer import IncrementalDetokenizer
    import inspect
    from pathlib import Path
    source = Path(inspect.getfile(IncrementalDetokenizer))
    require(source.is_file() and not source.is_symlink() and source.stat().st_size <= 1048576, "Pinned decoder source required", "IDENTITY")
    implementation = sha(source.read_bytes())

    def replay(prompt, tokens, reason, params):
        request = SimpleNamespace(request_id="nol-independent-decoder", prompt_token_ids=prompt, prompt_embeds=None, sampling_params=params)
        decoder = IncrementalDetokenizer.from_new_request(tokenizer, request)
        for index, token in enumerate(tokens): decoder.update([token], reason == "stop" and index == len(tokens) - 1)
        return {"text": decoder.get_next_output_text(True, False), "tokenIds": list(decoder.output_token_ids), "implementationSha256": implementation}
    return replay


def create_designated_engine(owned, controller, placement, descriptor):
    """Lazy real constructor seam. Only root may execute it after reviewing
    the source checkpoint and installing the approved fixed designation.
    Default None rejects BEFORE imports, file reads or engine construction.
    Private load authority precedes construction; the owned worker pauses it
    after actual weight loading until the parent releases the resident PID gate.
    """
    require(owned.NATIVE_RUNTIME_DESIGNATION is not None, "Native designation unavailable; no framework import attempted", "UNSUPPORTED")
    require(isinstance(placement, owned.PrivatePlacement) and "authorize_load" in placement.used and placement.startup == controller.plan and controller.phase == "loading", "Private actual load authority required", "CUSTODY")
    fields(descriptor, ("sourceId", "revision", "checkpointRoot", "workRoot", "model", "modelIdentityJson", "policy"))
    require(sha(canonical(descriptor).encode()) == controller.plan["requestPolicyDigest"], "Load descriptor differs from private policy seal", "IDENTITY")
    policy = descriptor["policy"]
    fields(policy, ("schema", "purpose", "allowedRecipes", "captureSiteIds", "maxCaptureBytes", "limits"))
    require(policy["schema"] == "omnius.nol.vllm-request-policy.v1" and policy["purpose"] in ("experiment", "conformance"), "Unknown request authority scope")
    integer(policy["maxCaptureBytes"], 0, 128 * 1048576)
    require(type(policy["captureSiteIds"]) is list and len(set(policy["captureSiteIds"])) == len(policy["captureSiteIds"]) <= 32, "Bounded distinct capture site policy required")
    require((policy["purpose"] == "conformance" and policy["captureSiteIds"] and policy["maxCaptureBytes"] > 0) or (policy["purpose"] == "experiment" and policy["captureSiteIds"] == [] and policy["maxCaptureBytes"] == 0), "Capture requires explicit conformance authority", "CUSTODY")
    require(type(policy["allowedRecipes"]) is list and len(policy["allowedRecipes"]) <= 256, "Bounded fixed recipe policy required", "CAPACITY")
    allowed = {}
    for entry in policy["allowedRecipes"]:
        fields(entry, ("recipeDigest", "operations"))
        require(type(entry["recipeDigest"]) is str and SHA.fullmatch(entry["recipeDigest"]) and entry["recipeDigest"] not in allowed and type(entry["operations"]) is list and 1 <= len(entry["operations"]) <= 2, "Invalid/repeated recipe policy", "IDENTITY")
        allowed[entry["recipeDigest"]] = clone(entry["operations"])
    require(descriptor["sourceId"] == "Qwen/Qwen3.5-4B" and descriptor["revision"] == "851bf6e806efd8d0a36b00ddf55e13ccb7b8cd0a" and controller.plan["gpuUuid"] == "GPU-3538758b-6ba7-fa1b-a80c-e315a606c3f0", "Only the explicitly approved source revision/A100 GPU0 is supported", "UNSUPPORTED")
    model = descriptor["model"]
    require(type(model) is dict and model.get("schema") == "omnius.nol.model.v1" and model.get("format") in ("hf", "safetensors") and model.get("quantization", {}).get("method") == "none", "Exact unquantized source manifest required", "UNSUPPORTED")
    require(model.get("modelDigest") == controller.plan["binding"]["modelDigest"] == owned.NATIVE_RUNTIME_DESIGNATION["modelDigest"], "Native model manifest differs from fixed designation", "IDENTITY")
    body = {key: value for key, value in model.items() if key not in ("id", "modelDigest")}
    identity = descriptor["modelIdentityJson"]
    require(type(identity) is str and len(identity.encode()) <= 1048576 and parse_json(identity) == body and sha(identity.encode()) == model["modelDigest"], "Full model identity bytes differ", "IDENTITY")
    from pathlib import Path
    root = Path(descriptor["checkpointRoot"])
    require(root.is_absolute() and root.resolve(strict=True) == root and root.is_dir() and not root.is_symlink(), "Canonical explicit checkpoint root required", "IDENTITY")
    work = Path(descriptor["workRoot"])
    import os
    require(work.is_absolute() and work.resolve(strict=True) == work and work.is_dir() and not work.is_symlink() and work.stat().st_uid == os.getuid() and work.stat().st_mode & 0o077 == 0, "Private owned canonical work root required", "IDENTITY")
    require(type(model.get("files")) is list and 1 <= len(model["files"]) <= 4096, "Complete bounded checkpoint inventory required", "CAPACITY")
    names, total = set(), 0
    for entry in model["files"]:
        fields(entry, ("path", "role", "artifact"))
        name, ref = entry["path"], entry["artifact"]
        require(type(name) is str and 0 < len(name) <= 1024 and "\\" not in name and not name.startswith("/") and all(p not in ("", ".", "..") for p in name.split("/")) and name not in names, "Normalized unique checkpoint file required", "IDENTITY")
        fields(ref, ("uri", "sha256", "sizeBytes", "mediaType"))
        require(type(ref["sha256"]) is str and SHA.fullmatch(ref["sha256"]) and ref["uri"] == "omnius-artifact://sha256/" + ref["sha256"], "Full checkpoint artifact required", "IDENTITY")
        integer(ref["sizeBytes"], 0, controller.plan["limits"]["maxLoadBytes"])
        path = root / name
        require(path.resolve(strict=True) == path and path.is_file() and not path.is_symlink(), "Checkpoint file escaped approved root", "IDENTITY")
        actual = owned.file_identity(path, controller.plan["limits"]["maxLoadBytes"] - total)
        require(actual == {"sha256": ref["sha256"], "sizeBytes": ref["sizeBytes"]}, "Full actual checkpoint bytes differ", "IDENTITY")
        total += actual["sizeBytes"]; names.add(name)
    actual_names = set()
    for index, path in enumerate(root.rglob("*")):
        require(index < 8192, "Checkpoint filesystem inventory bound exceeded", "CAPACITY")
        require(not path.is_symlink(), "Undeclared checkpoint symlink", "IDENTITY")
        if path.is_file(): actual_names.add(path.relative_to(root).as_posix())
    require(actual_names == names and "config.json" in names, "Checkpoint has extra/missing files", "IDENTITY")
    require((root / "config.json").stat().st_size <= 1048576, "Bounded native model config required", "CAPACITY")
    config = parse_json((root / "config.json").read_text("utf-8"))
    text = config.get("text_config", {})
    require(config.get("model_type") == "qwen3_5" and text.get("model_type") == "qwen3_5_text" and text.get("num_hidden_layers") == 32 and text.get("hidden_size") == 2560 and text.get("intermediate_size") == 9216 and text.get("hidden_act") == "silu" and not text.get("num_experts") and "quantization_config" not in config, "Unverified dense checkpoint architecture", "UNSUPPORTED")
    worker_type = owned.native_worker_class(controller, placement)
    # LOAD has been privately granted and source-owned guards are already armed.
    # Observe the sole broker-scoped device, never a default/alternate GPU.
    torch_module = worker_type._nol_source_guards.torch
    require(os.environ.get("CUDA_VISIBLE_DEVICES") == controller.plan["gpuUuid"] and
            torch_module.cuda.device_count() == 1 and torch_module.cuda.current_device() == 0,
            "Lease memory sizing requires the exact sole scoped CUDA device", "IDENTITY")
    _, total_device_bytes = torch_module.accelerator.get_memory_info(0)
    gpu_memory_utilization = lease_gpu_memory_utilization(controller.plan["reservedMiB"], total_device_bytes)
    qualified = worker_type.__module__ + "." + worker_type.__qualname__
    from vllm import LLM
    from vllm.config.compilation import CompilationMode, CUDAGraphMode
    from vllm.v1.engine.llm_engine import LLMEngine
    from nnsight.modeling.vllm.engines.engine import NNsightLLMEngine
    e = controller.plan["engine"]
    llm = LLM(str(root), tokenizer=str(root), trust_remote_code=False, dtype="bfloat16", worker_cls=qualified,
              gpu_memory_utilization=gpu_memory_utilization,
              distributed_executor_backend="uni", tensor_parallel_size=1, pipeline_parallel_size=1, data_parallel_size=1,
              enforce_eager=True, max_model_len=e["maxModelLen"], max_num_batched_tokens=e["maxNumBatchedTokens"], max_num_seqs=1,
              kv_cache_memory_bytes=e["kvCacheBytes"], enable_prefix_caching=False, enable_chunked_prefill=False,
              async_scheduling=False, language_model_only=True, enable_prompt_embeds=False, enable_lora=False,
              speculative_config=None, enable_sleep_mode=False, disable_log_stats=False, generation_config="vllm", seed=e["seed"],
              attention_config={"backend": "FLASH_ATTN"},
              compilation_config={"mode": CompilationMode.NONE, "cudagraph_mode": CUDAGraphMode.NONE},
              kernel_config={"enable_jit_warmup": False, "enable_cutedsl_warmup": False, "enable_flashinfer_autotune": False})
    engine = llm.llm_engine
    require(type(engine) is LLMEngine and all(hasattr(engine, name) for name in ("engine_core", "output_processor", "model_executor", "vllm_config", "add_request", "step", "abort_request", "has_unfinished_requests", "get_tokenizer", "collective_rpc")), "Pinned synchronous engine shape differs", "UNSUPPORTED")
    verify_lease_gpu_memory_utilization(engine.vllm_config.cache_config, gpu_memory_utilization)
    require(engine.log_stats is True, "Native RequestStateStats collection must be explicitly enabled", "IDENTITY")
    require("__init__" not in NNsightLLMEngine.__dict__, "NNsight engine gained constructor state", "IDENTITY")
    # Exact same-instance swap performed by pinned NNsight _load_sync.
    engine.__class__ = NNsightLLMEngine
    startup = controller.finish()
    guards = worker_type._nol_source_guards
    runner = guards.runner
    require(runner is not None, "Actual same-instance NNsight runner unavailable", "CUSTODY")
    sites = {}
    for site in model.get("tensorSites", []):
        if site.get("kind") == "mlp_intermediate":
            require(site.get("width") == 9216 and type(site.get("layer")) is int and 0 <= site["layer"] < 32 and site["id"] not in sites, "Dense site inventory differs", "IDENTITY")
            sites[site["id"]] = {**clone(site), "modulePath": "language_model.model.layers." + str(site["layer"]) + ".mlp"}
    require(sites and all(site in sites for site in policy["captureSiteIds"]), "Exact capture site inventory unavailable", "IDENTITY")
    from vllm.sampling_params import SamplingParams, RequestOutputKind
    import torch
    bridge = NativeRequestBridge(controller, guards, runner, torch, sites, controller.plan["binding"], controller.plan["source"], policy["maxCaptureBytes"])
    controller.request_bridge = bridge
    def authorize(operations, digest):
        require((digest is None and operations == []) or (digest in allowed and allowed[digest] == operations), "Operation outside fixed host policy", "CUSTODY")
    runtime = Runtime(engine=engine, tokenizer=engine.get_tokenizer(), sampling_params=lambda values: SamplingParams(**values, output_kind=RequestOutputKind.CUMULATIVE), replay_decoder=make_native_decoder_replay(engine.get_tokenizer()), bridge=bridge, authorize_operations=authorize, binding=controller.plan["binding"], source=controller.plan["source"], sites=sites, limits=policy["limits"])
    return {"entrypoint": llm, "engine": engine, "tokenizer": engine.get_tokenizer(), "startupObservation": startup, "runtime": runtime, "bridge": bridge, "workRoot": work, "policy": clone(policy)}


class NativeNeuronHooks:
    """Real module output hook plus actual down-projection input witness.
    torch_module/runner are host ports; this constructor never imports/loads.
    """
    def __init__(self, torch_module, runner, site_catalog):
        self.torch, self.runner, self.sites = torch_module, runner, clone(site_catalog)
        self.handles, self.operations, self.pending = [], [], None
        self.valid_rows, self.positions, self.hook_calls, self.witnesses = 0, [], 0, 0
        self.before_calls = self.before_witnesses = 0
        self.capture_site, self.capture_limit, self.capture_size, self.captures = None, 0, 0, []

    def install(self, operations, capture_site=None, capture_limit=0):
        require(not self.handles and not self.operations, "Native hook replay", "CUSTODY")
        self.operations = clone(operations)
        self.hook_calls = self.witnesses = 0
        self.capture_site, self.capture_limit, self.capture_size, self.captures = capture_site, capture_limit, 0, []
        if not operations and capture_site is None: return
        site = self.sites[capture_site if capture_site is not None else operations[0]["siteId"]]
        root = self.runner.get_model()
        module = root.get_submodule(site["modulePath"])
        require(type(module).__name__ == "Qwen2MoeMLP" and module.expert_gate is None and type(module.act_fn).__name__ == "SiluAndMul" and module.down_proj.input_size == 9216, "Actual dense module geometry differs", "UNSUPPORTED")
        self.handles.append(module.act_fn.register_forward_hook(self._edit))
        self.handles.append(module.down_proj.register_forward_pre_hook(self._witness))

    def computation(self, valid_rows, positions):
        require(self.pending is None, "Previous edited tensor was not witnessed", "CUSTODY")
        integer(valid_rows, 1, 256)
        require(type(positions) is list and len(positions) == valid_rows and all(type(v) is int and 0 <= v < 256 for v in positions), "Exact real computation positions required", "IDENTITY")
        self.valid_rows, self.positions = valid_rows, list(positions)
        self.before_calls, self.before_witnesses = self.hook_calls, self.witnesses

    def _edit(self, module, args, output):
        require(self.valid_rows > 0 and output.ndim == 2 and output.shape[1] == 9216 and self.valid_rows <= output.shape[0] <= 256 and output.dtype == self.torch.bfloat16 and output.is_cuda, "Native activation geometry/placement differs", "IDENTITY")
        require(self.pending is None, "Native activation call overlapped", "CUSTODY")
        if self.capture_site is not None:
            require(self.capture_size + self.valid_rows * 9216 * 2 * 3 <= self.capture_limit, "Native capture allowance exhausted before copying", "CAPACITY")
        edited = output.clone(memory_format=self.torch.contiguous_format)
        for op in self.operations:
            column = edited[:self.valid_rows, op["neuron"]]
            if op["operation"] == "NEURON_ADD": column.add_(op["amount"])
            else: column.mul_(op["factor"])
        require(bool(self.torch.isfinite(edited.narrow(0, 0, self.valid_rows)).all().item()), "Nonfinite valid native intervention", "CAPACITY")
        if self.capture_site is not None:
            self._capture_pending = {"positions": list(self.positions), "paddedRows": int(output.shape[0]), "before": self._bytes(output.narrow(0, 0, self.valid_rows)), "after": self._bytes(edited.narrow(0, 0, self.valid_rows)), "paddingBeforeSha256": sha(self._bytes(output.narrow(0, self.valid_rows, output.shape[0] - self.valid_rows))), "paddingAfterSha256": sha(self._bytes(edited.narrow(0, self.valid_rows, edited.shape[0] - self.valid_rows)))}
        self.pending = edited
        if self.operations: self.hook_calls += 1
        return edited

    def _witness(self, module, args):
        require(self.pending is not None and len(args) >= 1 and args[0].shape == self.pending.shape and args[0].dtype == self.pending.dtype and bool(self.torch.equal(args[0].contiguous().view(self.torch.uint16), self.pending.contiguous().view(self.torch.uint16))), "Down-projection consumed different activation bytes", "IDENTITY")
        if self.capture_site is not None:
            captured = self._capture_pending
            captured["consumed"] = self._bytes(args[0].narrow(0, 0, self.valid_rows))
            size = sum(len(captured[key]) for key in ("before", "after", "consumed"))
            require(self.capture_size + size <= self.capture_limit, "Native capture allowance exhausted", "CAPACITY")
            self.capture_size += size; self.captures.append(captured); self._capture_pending = None
        self.pending = None
        if self.operations: self.witnesses += 1

    def _bytes(self, tensor):
        return tensor.detach().contiguous().view(self.torch.uint8).cpu().numpy().tobytes(order="C")

    def finish_computation(self):
        require(self.pending is None and self.hook_calls == self.witnesses, "Native edited activation lacks actual consumption witness", "CUSTODY")
        expected = 1 if self.operations else 0
        require(self.hook_calls - self.before_calls == expected and self.witnesses - self.before_witnesses == expected, "Requested site was not observed exactly once in actual model forward", "CUSTODY")
        self.valid_rows, self.positions = 0, []

    def clear(self):
        for handle in self.handles: handle.remove()
        self.handles, self.operations, self.pending = [], [], None
        self.valid_rows, self.positions = 0, []


class NativeRequestBridge:
    """Fixed single-request scheduler bridge over the existing NNsight runner.
    It installs no trace/mediator/code and never replaces Requests or Envoy.
    All methods are internal source-owned ports, not serialized RPC methods.
    """
    def __init__(self, controller, guards, runner, torch_module, sites, binding, source, max_capture_bytes=0):
        require(sys.byteorder == "little", "Native BF16 capture byte order unsupported", "UNSUPPORTED")
        require(getattr(runner, "uses_mrope", None) is True and type(getattr(runner, "uses_xdrope_dim", None)) is int and runner.uses_xdrope_dim == 0,
                "Only the pinned Qwen3.5 text M-RoPE position layout is admitted", "UNSUPPORTED")
        self.controller, self.guards, self.runner, self.torch = controller, guards, runner, torch_module
        self.sites, self.binding, self.source = clone(sites), clone(binding), clone(source)
        self.hooks = NativeNeuronHooks(torch_module, runner, sites)
        self.maximum_capture = integer(max_capture_bytes, 0, 128 * 1048576)
        self.capture_site, self.request, self.forward_pending, self.sample_allowed = None, None, None, False
        self.engine_request_id = None
        self.forward_count, self.forward_positions, self.padded_positions, self.root_calls, self.sampler_calls = 0, [], 0, 0, 0
        self.generated = []

    def _nnsight(self):
        requests, interleaver = self.runner.nnsight_requests, self.runner.nnsight_model.interleaver
        require(type(requests.requests) is dict and type(requests.templates) is dict and type(requests.names) is dict and type(requests.out) is set, "Pinned NNsight request state shape differs", "IDENTITY")
        require(not requests.templates and not requests.names and not requests.out and not interleaver.mediators, "Unexpected registered trace/mediator state", "CUSTODY")
        return len(requests.requests), len(requests.templates)

    def memory_observation(self):
        return self.guards.memory_snapshot()

    def status(self):
        count, registered = self._nnsight()
        return {"schema": "omnius.nol.vllm-work.v1", "requestId": None if self.request is None else self.request["requestId"], "engineRequestId": self.engine_request_id, "activeRequestId": None if self.request is None else self.request["requestId"], "hooks": len(self.hooks.handles) if self.hooks.operations else 0, "observerHooks": len(self.hooks.handles) if self.capture_site is not None else 0, "nnsightRequests": count, "registeredBlocks": registered, "operations": [] if self.request is None else clone(self.request["operations"]), "forwardPositions": len(self.forward_positions), "forwards": self.forward_count, "sampledTokens": len(self.generated), "sampledTokenIds": list(self.generated), "hookCalls": self.hooks.hook_calls, "witnesses": self.hooks.witnesses, "paddedPositions": self.padded_positions, "positions": list(self.forward_positions)}

    def arm(self, request):
        require(self.request is None and not self.hooks.handles and self._nnsight() == (0, 0), "Native request replay/foreign custody", "CUSTODY")
        self.request = clone(request); self.forward_pending = None; self.engine_request_id = None
        self.forward_count, self.forward_positions, self.padded_positions, self.root_calls, self.sampler_calls, self.generated = 0, [], 0, 0, 0, []
        self.hooks.install(request["operations"], self.capture_site, self.maximum_capture)

    def bind_engine_request(self, request_id, internal_id):
        require(self.request is not None and self.request["requestId"] == request_id and self.engine_request_id is None and
                type(internal_id) is str and re.fullmatch(re.escape(request_id) + r"-[0-9a-f]{8}", internal_id) is not None,
                "Native internal request binding mismatch/replay", "IDENTITY")
        self.engine_request_id = internal_id

    def clear(self):
        self.hooks.clear(); self.request, self.forward_pending, self.sample_allowed = None, None, False
        self.engine_request_id = None
        require(self._nnsight() == (0, 0), "Actual NNsight requests remain; only official engine collect/abort may unwind them", "CUSTODY")

    @contextlib.contextmanager
    def scope(self, kind):
        c = self.controller
        require(c.phase == "ready" and c.active is None and self.request is not None and kind in ("execute", "sample"), "Unadmitted native request scope", "CUSTODY")
        c.phase, c.active = "request", {"kind": "request", "scope": kind}
        try: yield
        finally: c.active = None; c.phase = "ready"

    def before_execute(self, scheduler):
        require(self.request is not None and self.forward_pending is None, "Unexpected scheduler execution", "CUSTODY")
        rid = self.engine_request_id
        require(rid is not None, "Actual internal request binding absent before scheduler execution", "CUSTODY")
        expected = len(self.request["promptTokenIds"]) if not self.generated else 1
        require(type(scheduler.num_scheduled_tokens) is dict and scheduler.num_scheduled_tokens == {rid: expected} and scheduler.total_num_scheduled_tokens == expected, "Foreign/chunked/preempted scheduler rows", "UNSUPPORTED")
        require(not scheduler.scheduled_spec_decode_tokens and not scheduler.scheduled_encoder_inputs and not any(scheduler.num_common_prefix_blocks), "Unreviewed speculation/encoder/prefix reuse", "UNSUPPORTED")
        require(len(scheduler.scheduled_new_reqs) == (0 if self.generated else 1), "Unreviewed scheduler new-request inventory", "CUSTODY")
        for data in scheduler.scheduled_new_reqs:
            require(data.req_id == rid and list(data.prompt_token_ids) == self.request["promptTokenIds"] and getattr(data.sampling_params, "extra_args", None) in (None, {}), "Native prompt/trace payload differs", "IDENTITY")
        self.forward_pending = expected

    @contextlib.contextmanager
    def model_forward(self, kwargs):
        require(self.forward_pending is not None and self.controller.active == {"kind": "request", "scope": "execute"}, "Model forward outside exact scheduler admission", "CUSTODY")
        require(kwargs.get("inputs_embeds") is None and kwargs.get("intermediate_tensors") is None, "Embedding/pipeline input unsupported", "UNSUPPORTED")
        values, positions = kwargs.get("input_ids"), kwargs.get("positions")
        # Pinned Qwen3.5 uses three-axis M-RoPE even for text-only prompts.
        # Inspect only metadata and the admitted real prefix; padding may be
        # uninitialized and is neither interpreted nor counted as extra tokens.
        def metadata(tensor):
            if tensor is None: return "none"
            return "shape=" + str(tuple(tensor.shape)[:4]) + ",dtype=" + str(tensor.dtype)[:64] + ",device=" + str(tensor.device)[:64]
        detail = " | input_ids(" + metadata(values) + ") positions(" + metadata(positions) + ")"
        require(values is not None and positions is not None and values.ndim == 1 and positions.ndim == 2 and
                tuple(positions.shape) == (3, values.shape[0]) and self.forward_pending <= values.shape[0] <= 256 and
                values.dtype == self.torch.int32 and positions.dtype == self.torch.int64 and values.is_cuda and positions.is_cuda and
                values.device.type == positions.device.type == "cuda" and values.device.index == positions.device.index == 0,
                "Actual pinned Qwen3.5 token/M-RoPE tensor geometry differs" + detail, "IDENTITY")
        n = self.forward_pending
        actual_ids = values[:n].detach().cpu().tolist(); position_axes = positions[:, :n].detach().cpu().tolist()
        expected_ids = self.request["promptTokenIds"] if not self.generated else [self.generated[-1]]
        start = 0 if not self.generated else len(self.request["promptTokenIds"]) + len(self.generated) - 1
        expected_positions = list(range(start, start + n))
        require(actual_ids == expected_ids and position_axes == [expected_positions, expected_positions, expected_positions],
                "Actual scheduled input IDs/text M-RoPE axes differ" + detail, "IDENTITY")
        actual_positions = position_axes[0]
        require(len(self.forward_positions) + n <= self.request["maxForwardPositions"] and self.forward_count < self.request["maxTokens"], "Native forward budget exhausted", "CAPACITY")
        self.hooks.computation(n, actual_positions); self.root_calls = 0
        try:
            yield
            self.hooks.finish_computation(); require(self.root_calls == 1, "Real model forward not independently observed exactly once", "CUSTODY")
            self.forward_count += 1; self.forward_positions.extend(actual_positions); self.padded_positions += int(values.shape[0]) - n
            self.forward_pending = None
        except BaseException:
            raise

    def observed_root(self):
        require(self.forward_pending is not None and self.controller.active == {"kind": "request", "scope": "execute"}, "Unclassified native real-model invocation", "CUSTODY")
        self.root_calls += 1; require(self.root_calls == 1, "Extra native model invocation", "CUSTODY")

    @contextlib.contextmanager
    def sampling(self):
        require(self.request is not None and not self.sample_allowed and self.forward_count == len(self.generated) + 1 and self.forward_pending is None, "Sampler order differs from actual forward", "CUSTODY")
        self.sample_allowed, self.sampler_calls = True, 0
        try: yield
        finally: self.sample_allowed = False

    def observed_sampler(self, rows):
        require(self.sample_allowed and rows == 1 and self.sampler_calls == 0, "Unclassified/duplicate native sample", "CUSTODY")
        self.sampler_calls += 1

    def sampled(self, output):
        actual = output.sampled_token_ids.detach().cpu().tolist()
        require(self.sample_allowed and self.sampler_calls == 1 and type(actual) is list and len(actual) == 1 and type(actual[0]) is list and len(actual[0]) == 1, "Actual sampler tensor geometry differs", "IDENTITY")
        token = integer(actual[0][0], 0, UINT); self.generated.append(token)

    def capture(self, request_id, recipe_digest, prompt_ids, operations):
        require(self.capture_site is not None and self.maximum_capture > 0 and self.hooks.captures and self.forward_count == len(self.hooks.captures), "No actual bounded capture available", "CUSTODY")
        import struct
        arrays, forwards, payload, offset = [], [], [], 0
        width = self.sites[self.capture_site]["width"]
        for i, cell in enumerate(self.hooks.captures):
            forwards.append({"index": i, **{k: cell[k] for k in ("positions", "paddedRows", "paddingBeforeSha256", "paddingAfterSha256")}})
            for name in ("before", "after", "consumed"):
                raw = cell[name]; arrays.append({"name": "f" + str(i) + "." + name, "shape": [len(cell["positions"]), width], "dtype": "bf16", "offset": offset, "sizeBytes": len(raw), "sha256": sha(raw)})
                offset += len(raw); payload.append(raw)
        header = canonical({"schema": "omnius.nol.vllm-capture.v1", "binding": self.binding, "source": self.source, "requestId": request_id, "siteId": self.capture_site, "recipeDigest": recipe_digest, "promptTokenIds": prompt_ids, "operations": operations, "arrays": arrays, "forwards": forwards}).encode()
        raw = b"NOLVLC01" + struct.pack(">I", len(header)) + header + b"".join(payload)
        require(len(header) <= 1048576 and len(raw) <= self.maximum_capture, "Bounded capture publication exceeded", "CAPACITY")
        return raw

