# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-attribute-span-cost-when-otel-context-propagation-severs-at-a-tool-call-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-attribute-span-cost-when-otel-context-propagation-severs-at-a-tool-call-boundary.warrant.json
# Markdown SHA-256:   fe65cfadd9642df21a002b3c2047e6f7b71945c1ebc513612bf49b92b1208709
# Code AST SHA-256:   7786858d68fc7d83d89a7174026f3c0f1b40f3093d31a257c38b662a908b16ca
# Verified Classes:   AttributionInvariantViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class AttributionInvariantViolation(RuntimeError):
    """Raised when per-turn cost attribution cannot be reconciled to the span ledger."""
    pass


def reconcile_turn_costs(spans: list[dict], tolerance_usd: float = 1e-6) -> dict[str, float]:
    """
    Reconcile cost-bearing spans against explicit turn tokens.

    Invariant: every span carrying cost_usd > 0 MUST carry a turn_id attribute.
    A span that is a trace root (parent_span_id is None) but has cost is the
    orphan condition produced by severed context propagation across a tool
    boundary. We refuse to silently bucket it as 'unattributed'.
    """
    per_turn: dict[str, float] = {}
    orphans: list[dict] = []

    for span in spans:
        cost = span.get("cost_usd", 0.0)
        if cost <= 0:
            continue
        turn_id = span.get("attributes", {}).get("turn_id")
        if turn_id is None:
            # Cost exists but no accounting key survived transport.
            orphans.append(span)
            continue
        per_turn[turn_id] = per_turn.get(turn_id, 0.0) + cost

    total_ledger = sum(s.get("cost_usd", 0.0) for s in spans)
    total_attributed = sum(per_turn.values())
    residual = total_ledger - total_attributed

    if orphans:
        raise AttributionInvariantViolation(
            f"{len(orphans)} cost-bearing span(s) lack a turn_id; "
            f"residual ${residual:.6f} across trace roots "
            f"{[s.get('trace_id') for s in orphans][:5]}. "
            f"Context propagation severed at a tool boundary; "
            f"rejoin via explicit turn token before trusting per-turn cost."
        )

    if abs(residual) > tolerance_usd:
        raise AttributionInvariantViolation(
            f"Attribution residual ${residual:.6f} exceeds tolerance "
            f"${tolerance_usd:.6f}; ledger and turn aggregation diverged."
        )

    return per_turn
