# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-span-level-token-accounting-when-a-sub-agent-s-trace-context-is-re-parented-across-an-asynchronous-mcp-tool-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-span-level-token-accounting-when-a-sub-agent-s-trace-context-is-re-parented-across-an-asynchronous-mcp-tool-boundary.warrant.json
# Markdown SHA-256:   77d8ed8413a6bedd97fef2627ac0c6fb51e3d99d79adea359ab45f3fd90c218c
# Code AST SHA-256:   e72c21d52377a3889c222d683b3fb438288b701d080e644637da9e49a64734b6
# Verified Classes:   TraceAttributionError, SpanRecord, ProviderUsage
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional

class TraceAttributionError(RuntimeError):
    """Raised when a child span's cost cannot be reconciled to a root trace."""
    pass

@dataclass
class SpanRecord:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    input_tokens: int
    output_tokens: int
    sampled: bool
    message_id: Optional[str] = None

@dataclass
class ProviderUsage:
    trace_id: str
    total_tokens: int

def reconcile_cost(
    spans: list[SpanRecord],
    provider: list[ProviderUsage],
    dedup_ttl_seconds: int,
    redelivery_window_seconds: int,
) -> dict[str, int]:
    if redelivery_window_seconds > dedup_ttl_seconds:
        raise TraceAttributionError(
            f"Broker redelivery window ({redelivery_window_seconds}s) exceeds "
            f"dedup TTL ({dedup_ttl_seconds}s); parent-first idempotency cannot be guaranteed."
        )

    attributed: dict[str, int] = {}
    seen_message_ids: set[tuple[str, str]] = set()

    for span in spans:
        if not span.sampled:
            raise TraceAttributionError(
                f"Span {span.span_id} in trace {span.trace_id} has sampled=0; "
                "sampling-flag fidelity violated at a boundary."
            )
        if span.message_id is not None:
            key = (span.trace_id, span.message_id)
            if key in seen_message_ids:
                continue  # redelivery suppressed
            seen_message_ids.add(key)
        attributed[span.trace_id] = attributed.get(span.trace_id, 0) + (
            span.input_tokens + span.output_tokens
        )

    provider_map = {u.trace_id: u.total_tokens for u in provider}
    for trace_id, cost in attributed.items():
        expected = provider_map.get(trace_id)
        if expected is None:
            raise TraceAttributionError(
                f"Attributed cost for trace {trace_id} has no provider usage record."
            )
        if cost != expected:
            raise TraceAttributionError(
                f"Reconciliation gap on trace {trace_id}: attributed={cost}, "
                f"provider={expected}, gap={abs(cost - expected)}."
            )

    return attributed
