# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reconcile-opentelemetry-genai-token-accounting-spans-when-a-delegated-sub-agent-re-emits-the-parent-s-prompt-pr.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reconcile-opentelemetry-genai-token-accounting-spans-when-a-delegated-sub-agent-re-emits-the-parent-s-prompt-pr.warrant.json
# Markdown SHA-256:   f38a457efd60f5f30923d6a6433f4b62c0cceaab256b43590b2b1bd40f74b8b5
# Code AST SHA-256:   2ae6748b4bb90c9820d0a8a1dc5422fe03ce8e8472a3adb39c7600e13049c9b6
# Verified Classes:   PrefixOverlapUnreconciled, GenAISpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class PrefixOverlapUnreconciled(RuntimeError):
    """Raised when a trace rollup cannot dedupe shared prompt prefixes."""


@dataclass
class GenAISpan:
    span_id: str
    parent_span_id: str | None
    input_tokens: int
    output_tokens: int
    prefix_hash: str | None  # hash of shared prompt prefix; None if absent


def reconcile_trace_tokens(spans: list[GenAISpan]) -> int:
    """
    Compute logical input tokens for a trace by deduplicating shared prefixes.
    Every span must expose a prefix_hash OR be a leaf with no ancestor overlap.
    """
    by_id = {s.span_id: s for s in spans}
    seen_prefixes: set[str] = set()
    logical_input = 0

    for span in spans:
        if span.prefix_hash is None:
            # No prefix hash: only safe if span has no parent (root) or parent
            # has no overlapping input. We cannot prove disjointness, so refuse.
            if span.parent_span_id is not None:
                raise PrefixOverlapUnreconciled(
                    f"span {span.span_id} has parent {span.parent_span_id} "
                    f"but no prefix_hash; shared-prefix overlap unprovable"
                )
            logical_input += span.input_tokens
            continue

        if span.prefix_hash in seen_prefixes:
            # Prefix already counted by an ancestor/peer; count only the novel
            # remainder. We conservatively attribute 0 to avoid double-count.
            continue

        seen_prefixes.add(span.prefix_hash)
        logical_input += span.input_tokens

    # Outputs of non-leaf spans re-enter as inputs downstream; only leaf
    # outputs are terminal. Sum leaf outputs only.
    leaf_outputs = sum(
        s.output_tokens
        for s in spans
        if not any(c.parent_span_id == s.span_id for c in spans)
    )
    return logical_input + leaf_outputs


def publish_trace_cost(spans: list[GenAISpan]) -> int:
    if not spans:
        raise PrefixOverlapUnreconciled("empty trace: nothing to reconcile")
    total = reconcile_trace_tokens(spans)
    if total <= 0:
        raise PrefixOverlapUnreconciled(
            "reconciled token total collapsed to zero; topology suspect"
        )
    return total
