# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-genai-span-whose-tool-call-attributes-are-structurally-valid-but-semantically-orphaned.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-genai-span-whose-tool-call-attributes-are-structurally-valid-but-semantically-orphaned.warrant.json
# Markdown SHA-256:   4a8cd71a796e94d2cedac02b5ad0ed9a1cdbbe3cdc5dcc5d798daf495b27570c
# Code AST SHA-256:   e34c540c7157eed946c557cb8af2d525fea94e675457f6b9f6c745a1176962f5
# Verified Classes:   OrphanedToolCausalityError, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class OrphanedToolCausalityError(RuntimeError):
    """Raised when a chat span's causal link to a prior tool call cannot be
    established by declared reference and fails token reconciliation."""


@dataclass
class Span:
    name: str
    operation: str
    parent: Optional[str]
    tool_call_id: Optional[str] = None
    consumed_tool_call_id: Optional[str] = None  # declared edge, if emitted
    input_tokens: int = 0
    output_tokens: int = 0
    tool_result_tokens: int = 0


def reconstruct_transition(prior_chat: Span, tool: Span, followup: Span, tolerance: int = 16) -> str:
    # Declared edge is the only sufficient condition.
    if followup.consumed_tool_call_id == tool.tool_call_id and tool.tool_call_id:
        return "declared"

    # Otherwise attempt reconciliation: did the followup's input grow by the
    # tool result's size relative to the prior chat's context?
    delta = followup.input_tokens - (prior_chat.input_tokens + prior_chat.output_tokens)
    if abs(delta - tool.tool_result_tokens) <= tolerance:
        return "inferred-reconciled"

    raise OrphanedToolCausalityError(
        f"tool_call_id={tool.tool_call_id!r} has no declared consumer and "
        f"token delta {delta} does not reconcile with tool_result_tokens "
        f"{tool.tool_result_tokens} (tol={tolerance}); refusing to distill "
        f"transition across orphaned span boundary"
    )
