# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-attribute-token-cost-across-an-otel-span-tree-when-a-single-llm-call-is-re-emitted-by-a-retry-a-fan-out-and-a-memory-write-side.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-attribute-token-cost-across-an-otel-span-tree-when-a-single-llm-call-is-re-emitted-by-a-retry-a-fan-out-and-a-memory-write-side.warrant.json
# Markdown SHA-256:   f94ab98fb4ec126efa66cd797001bd2e7383eaf2ca396187880869143c88688b
# Code AST SHA-256:   52d13630e942fcc87f69a8f2ff38c47a8a8689b1b375ecd051e94ca0a69bc511
# Verified Classes:   AttributionInvariantError, Span, Ledger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class AttributionInvariantError(RuntimeError):
    """Raised when a span tree cannot be reconciled without guessing cost ownership."""
    pass


@dataclass
class Span:
    span_id: str
    logical_op_id: str
    parent_id: Optional[str]
    agent_id: str
    tool_name: Optional[str]
    attempt: int
    input_tokens: int
    output_tokens: int
    billed: Optional[bool]          # None => attestation missing
    finish_reason: Optional[str]    # "cancelled" => fan-out loser
    fanout_owner_span_id: Optional[str] = None


@dataclass
class Ledger:
    by_agent: dict = field(default_factory=dict)
    by_tool: dict = field(default_factory=dict)
    by_memory_op: dict = field(default_factory=dict)
    unattributed: list = field(default_factory=list)


def reconcile(spans: list[Span], memory_op_prefix: str = "tool.memory.") -> Ledger:
    ledger = Ledger()
    # Group by logical operation: the unit of billing.
    ops: dict[str, list[Span]] = {}
    for s in spans:
        ops.setdefault(s.logical_op_id, []).append(s)

    for op_id, group in ops.items():
        # Resolve fan-out owner; losers are zero-cost.
        owner_id = next((s.fanout_owner_span_id for s in group
                         if s.fanout_owner_span_id), None)
        billable = [s for s in group
                    if s.finish_reason != "cancelled"
                    and (owner_id is None or s.span_id == owner_id)]

        # Attempt deduplication requires transport attestation.
        for s in billable:
            if s.billed is None:
                raise AttributionInvariantError(
                    f"span {s.span_id} (op {op_id}) lacks gen_ai.request.billed; "
                    f"cannot distinguish pre-flight abort from billed retry. "
                    f"Route to unattributed bucket, do not guess."
                )

        billed_attempts = [s for s in billable if s.billed]
        if not billed_attempts:
            continue
        # Sum across billed attempts: input tokens are re-billed per attempt.
        cost_in = sum(s.input_tokens for s in billed_attempts)
        cost_out = sum(s.output_tokens for s in billed_attempts)

        # Memory-write side effects are charged to the memory node, not the agent.
        mem_owner = next((s for s in billed_attempts
                          if s.tool_name and s.tool_name.startswith(memory_op_prefix)),
                         None)
        if mem_owner is not None:
            ledger.by_memory_op[mem_owner.tool_name] = (
                ledger.by_memory_op.get(mem_owner.tool_name, (0, 0))
            )
            prev = ledger.by_memory_op[mem_owner.tool_name]
            ledger.by_memory_op[mem_owner.tool_name] = (
                prev[0] + cost_in, prev[1] + cost_out
            )
            # Agent gets a reference edge, not the tokens.
            ledger.by_agent.setdefault(mem_owner.agent_id, (0, 0))
        else:
            a = billed_attempts[0].agent_id
            prev = ledger.by_agent.get(a, (0, 0))
            ledger.by_agent[a] = (prev[0] + cost_in, prev[1] + cost_out)
            if billed_attempts[0].tool_name:
                t = billed_attempts[0].tool_name
                pv = ledger.by_tool.get(t, (0, 0))
                ledger.by_tool[t] = (pv[0] + cost_in, pv[1] + cost_out)

    return ledger
