# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-span-closure-when-a-tool-call-s-token-accounting-diverges-from-its-parent-agent-span.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-span-closure-when-a-tool-call-s-token-accounting-diverges-from-its-parent-agent-span.warrant.json
# Markdown SHA-256:   9d5668afcdbc2081cb73188a9bc4249786d1ef61c1dcd87f39ed698d6263e638
# Code AST SHA-256:   d77d91c721a22b347c422ebd2ffa9de2ea555149e65d502f83d33c3e3deb364f
# Verified Classes:   UsageReconciliationError, GenAISpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class UsageReconciliationError(RuntimeError):
    """Raised when a GenAI span's token accounting cannot be reconciled
    against its parent agent span under the semantic conventions."""


@dataclass
class GenAISpan:
    span_id: str
    operation_name: str            # "invoke_agent" | "execute_tool" | ...
    input_tokens: int = 0
    output_tokens: int = 0
    request_model: Optional[str] = None   # marks a model-backed tool
    usage_is_estimate: bool = False
    children: list = field(default_factory=list)
    closed: bool = False


def child_set_hash(children: list) -> str:
    h = hashlib.sha256()
    for c in sorted(children, key=lambda s: s.span_id):
        h.update(c.span_id.encode())
    return h.hexdigest()[:16]


def close_agent_span(parent: GenAISpan, policy: str = "deferred") -> str:
    if parent.operation_name != "invoke_agent":
        raise UsageReconciliationError(
            f"span {parent.span_id} is not an agent span; cannot reconcile"
        )
    if parent.usage_is_estimate:
        # A pre-flight estimate cannot anchor reconciliation: the parent's
        # tokens may not include the downstream effect of tool output.
        raise UsageReconciliationError(
            f"parent {parent.span_id} carries estimated usage; "
            "reconciliation is undefined until actual usage is stamped at close"
        )

    unmarked = [
        c for c in parent.children
        if c.output_tokens > 0 and c.request_model is None
    ]
    if unmarked:
        if policy == "strict":
            raise UsageReconciliationError(
                f"child spans {[c.span_id for c in unmarked]} report output "
                "tokens without gen_ai.request.model; cannot distinguish "
                "model-backed tool from mis-instrumented deterministic tool"
            )
        # deferred: stamp divergence, exclude from aggregates
        parent.closed = True
        return f"reconciliation=divergent unmarked={len(unmarked)}"

    open_children = [c for c in parent.children if not c.closed]
    if open_children and policy == "strict":
        raise UsageReconciliationError(
            f"parent {parent.span_id} closing before children "
            f"{[c.span_id for c in open_children]}; child set incomplete, "
            "monotonicity check would be vacuous"
        )

    parent.closed = True
    return (
        f"reconciliation=deferred child_set_hash={child_set_hash(parent.children)} "
        f"open_children={len(open_children)}"
    )
