# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-genai-semantic-convention-span-attributes-from-silently-mis-accounting-tokens-and-cost-across-agent-tool-call-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-genai-semantic-convention-span-attributes-from-silently-mis-accounting-tokens-and-cost-across-agent-tool-call-boundaries.warrant.json
# Markdown SHA-256:   404d7713d30bf8c7d35b0d4533c091d161ad09e77a488f7eb21a4938a1d265d5
# Code AST SHA-256:   ae93e638fc29b7ac92bb62b485f405d36bd648d78b1edbc777d2af07c9fb3f67
# Verified Classes:   UsageAccountingInvariantError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class UsageAccountingInvariantError(RuntimeError):
    """Raised when a GenAI span tree violates the additive-usage contract."""
    pass


INFERENCE_OPS = frozenset({"chat", "text_completion", "embeddings"})
ORCHESTRATION_OPS = frozenset({"invoke_agent", "create_agent", "execute_tool"})


def reconcile_usage(span_tree: list[dict], sampling_rate: float = 1.0) -> int:
    """Return the deduplicated token total for a trace, or raise.

    Enforces: usage only on inference ops, dedup by response id,
    and parent claims must match the sum of their inference descendants.
    """
    if not 0.0 < sampling_rate <= 1.0:
        raise UsageAccountingInvariantError(f"invalid sampling_rate {sampling_rate}")

    seen_response_ids: set[str] = set()
    total = 0
    claims: list[tuple[str, int]] = []

    for span in span_tree:
        op = span.get("gen_ai.operation.name")
        usage = span.get("gen_ai.usage.total_tokens")

        if op in ORCHESTRATION_OPS and usage is not None:
            raise UsageAccountingInvariantError(
                f"orchestration span {span.get('span_id')} carries usage={usage}; "
                "usage must not propagate to non-inference spans"
            )

        if op in INFERENCE_OPS and usage is not None:
            rid = span.get("gen_ai.response.id")
            if rid is None:
                raise UsageAccountingInvariantError(
                    f"inference span {span.get('span_id')} missing gen_ai.response.id; "
                    "cannot deduplicate retried attempts"
                )
            if rid in seen_response_ids:
                continue
            seen_response_ids.add(rid)
            total += usage

        if op in ORCHESTRATION_OPS and span.get("usage_claim") is not None:
            claims.append((span.get("span_id"), span["usage_claim"]))

    if sampling_rate < 1.0:
        total = int(round(total / sampling_rate))

    for span_id, claim in claims:
        if abs(claim - total) > max(1, int(0.02 * total)):
            raise UsageAccountingInvariantError(
                f"parent span {span_id} claims {claim} tokens but inference "
                f"descendants reconcile to {total} (sampling_rate={sampling_rate})"
            )

    return total
