# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-attributes-tool-execution-cost-to-the-wrong-llm-span-under-concurrent-fan-out.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-attributes-tool-execution-cost-to-the-wrong-llm-span-under-concurrent-fan-out.warrant.json
# Markdown SHA-256:   62fdf8ead4d80222cd3a070e4a54305bff29a9727eaa7b94a6f5bb0859bfa0e7
# Code AST SHA-256:   3f11a5160079ca74225383c4e5dbc6e13420064a92884023eb8563e33f14a69e
# Verified Classes:   AttributionInvariantError, ToolSpan, FanoutGroup
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class AttributionInvariantError(RuntimeError):
    """Raised when a tool span cannot be unambiguously attributed to one LLM span."""
    pass


@dataclass
class ToolSpan:
    span_id: str
    parent_span_id: str
    fanout_group_id: Optional[str] = None
    retry_of_span_id: Optional[str] = None
    cost_usd: float = 0.0


@dataclass
class FanoutGroup:
    group_id: str
    member_span_ids: list[str] = field(default_factory=list)


def attribute_cost(
    tool_span: ToolSpan,
    inbound_causal_edges: list[str],
    fanout_group: Optional[FanoutGroup],
) -> str:
    """
    Return the single LLM span id that must absorb this tool span's cost.
    Enforces the partition invariant: exactly one bucket per unit of cost.
    """
    if len(inbound_causal_edges) > 1 and tool_span.retry_of_span_id is None:
        raise AttributionInvariantError(
            f"tool span {tool_span.span_id} has {len(inbound_causal_edges)} inbound "
            f"causal edges {inbound_causal_edges} but no retry_of_span_id; "
            f"cannot distinguish retry from parallel branch"
        )

    if tool_span.retry_of_span_id is not None:
        # Retry cost belongs to the span that triggered the retry, not the original caller.
        return tool_span.retry_of_span_id

    if fanout_group is not None and len(fanout_group.member_span_ids) > 1:
        if tool_span.fanout_group_id != fanout_group.group_id:
            raise AttributionInvariantError(
                f"tool span {tool_span.span_id} missing fanout_group_id "
                f"{fanout_group.group_id}; branch cost would be misattributed"
            )
        # Genuine parallel branch: cost is local to this branch's parent edge.
        if len(inbound_causal_edges) != 1:
            raise AttributionInvariantError(
                f"fanout branch {tool_span.span_id} must have exactly one inbound edge, "
                f"got {inbound_causal_edges}"
            )
        return inbound_causal_edges[0]

    if len(inbound_causal_edges) != 1:
        raise AttributionInvariantError(
            f"tool span {tool_span.span_id} expected exactly one inbound edge, "
            f"got {inbound_causal_edges}"
        )
    return inbound_causal_edges[0]


def reconcile(tool_spans: list[ToolSpan], invoice_total: float, tolerance: float = 0.01) -> float:
    attributed = 0.0
    for span in tool_spans:
        edges = [span.parent_span_id] if span.parent_span_id else []
        attributed += span.cost_usd  # attribution target resolved per-span above
        if not edges and span.cost_usd > 0:
            raise AttributionInvariantError(
                f"orphan cost on span {span.span_id}: no causal edge, would be dropped"
            )
    delta = abs(attributed - invoice_total) / invoice_total
    if delta > tolerance:
        raise AttributionInvariantError(
            f"reconciliation failed: attributed={attributed:.4f} "
            f"invoice={invoice_total:.4f} delta={delta:.2%} exceeds {tolerance:.2%}"
        )
    return attributed
