# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-token-cost-attribution-when-an-agent-span-resumes-across-a-tool-call-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-token-cost-attribution-when-an-agent-span-resumes-across-a-tool-call-boundary.warrant.json
# Markdown SHA-256:   c0991863152d1ff50640cc7957ca88b4d6fde0ae400e1da601a6d31e58c78121
# Code AST SHA-256:   e68bc15fe39b3f335e81d8b9eb4412d5bb39517b052ac0d2dcc2e18f3feb308e
# Verified Classes:   UnattributedTokenUsageError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UnattributedTokenUsageError(RuntimeError):
    """Raised when a resumed agent span's usage cannot be reconciled to a
    unique logical operation without double-counting re-sent context."""
    pass


def reconcile_operation_usage(spans: list[dict]) -> dict:
    """
    Reconstruct the authoritative usage vector for one logical agent operation
    from its spans, enforcing the lineage invariant:
      every consumed token belongs to exactly one span,
      and resumed spans declare their re-sent context via
      gen_ai.agent.resume.from_span_id.
    """
    by_id = {s["span_id"]: s for s in spans}
    total_input = 0
    total_output = 0
    seen_origins = set()

    for span in spans:
        if span.get("gen_ai.operation.name") != "chat":
            continue

        origin = span.get("gen_ai.agent.resume.from_span_id")
        if origin is None:
            # Fresh work: full usage is attributable to this span.
            total_input += span["gen_ai.usage.input_tokens"]
            total_output += span["gen_ai.usage.output_tokens"]
            seen_origins.add(span["span_id"])
            continue

        # Resumed span: input tokens include re-sent context that was
        # already counted on the origin span. Subtract the origin's
        # input to avoid double-counting; count only the delta.
        if origin not in by_id:
            raise UnattributedTokenUsageError(
                f"span {span['span_id']} declares resume origin {origin} "
                f"but that span is absent from the trace; usage cannot be "
                f"attributed without double-counting or silent loss"
            )
        if origin in seen_origins:
            raise UnattributedTokenUsageError(
                f"span {span['span_id']} resumes from {origin}, which was "
                f"already counted as fresh work; lineage cycle or "
                f"mis-tagged retry"
            )

        origin_input = by_id[origin]["gen_ai.usage.input_tokens"]
        delta_input = span["gen_ai.usage.input_tokens"] - origin_input
        if delta_input < 0:
            raise UnattributedTokenUsageError(
                f"resumed span {span['span_id']} reports fewer input tokens "
                f"({span['gen_ai.usage.input_tokens']}) than its origin "
                f"({origin_input}); re-sent context cannot shrink"
            )
        total_input += delta_input
        total_output += span["gen_ai.usage.output_tokens"]
        seen_origins.add(span["span_id"])

    return {"input_tokens": total_input, "output_tokens": total_output}
