# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-successful-tool-span-as-a-hallucinated-invocation-rather-than-a-real-one.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-successful-tool-span-as-a-hallucinated-invocation-rather-than-a-real-one.warrant.json
# Markdown SHA-256:   8f41154933784976fd3719914a8b786f2948cfa7dbb9e9419280b4c376e1d55c
# Code AST SHA-256:   b9ae2ba170516f8b7935ae8ed4198024be77f3614612be0097dffa7b32ff71ce
# Verified Classes:   HallucinatedInvocationError, ToolSpan, TransportRecord
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class HallucinatedInvocationError(RuntimeError):
    """Raised when a tool span has no causal anchor in the transport log."""


@dataclass(frozen=True)
class ToolSpan:
    span_id: str
    call_id: str
    turn_id: str
    status: str
    provenance: Optional[str]  # "transport" | "adapter-repair" | "regex-extract" | "fallback-synth" | None
    result_bytes: Optional[bytes]


@dataclass(frozen=True)
class TransportRecord:
    call_id: str
    turn_id: str
    response_bytes: bytes


def anchor_span(span: ToolSpan, transport_log: dict[str, TransportRecord]) -> TransportRecord:
    """Return the transport record that causally anchors this span, or raise."""
    if span.provenance is None:
        raise HallucinatedInvocationError(
            f"span {span.span_id} has no provenance; treated as fabricated"
        )
    if span.provenance != "transport":
        raise HallucinatedInvocationError(
            f"span {span.span_id} provenance={span.provenance!r} is not transport-anchored; "
            f"result must not be consumed as ground truth"
        )
    record = transport_log.get(span.call_id)
    if record is None:
        raise HallucinatedInvocationError(
            f"span {span.span_id} call_id={span.call_id!r} absent from transport log"
        )
    if record.turn_id != span.turn_id:
        raise HallucinatedInvocationError(
            f"span {span.span_id} turn_id={span.turn_id!r} mismatches transport turn "
            f"{record.turn_id!r}; stale or reused span id"
        )
    if span.result_bytes is not None and span.result_bytes != record.response_bytes:
        raise HallucinatedInvocationError(
            f"span {span.span_id} result bytes diverge from transport response; "
            f"possible response tampering"
        )
    return record


def consume_tool_result(span: ToolSpan, transport_log: dict[str, TransportRecord]) -> bytes:
    """Gate downstream reasoning on anchoring. Never returns unanchored bytes."""
    record = anchor_span(span, transport_log)
    return record.response_bytes
