# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reconcile-opentelemetry-genai-span-attributes-against-tool-call-side-effects-before-finalizing-token-accounting.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reconcile-opentelemetry-genai-span-attributes-against-tool-call-side-effects-before-finalizing-token-accounting.warrant.json
# Markdown SHA-256:   1451e470df07875394c87fb1de94c4f38ceb490a62ff07eed547a7a820fa7f13
# Code AST SHA-256:   3bf1d12eb68a15e4920e15e2426df93a26aeff15454c980615628af82ab8567c
# Verified Classes:   UnreconciledTokenAccounting, ToolCallSpan, HarnessPayload
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class UnreconciledTokenAccounting(RuntimeError):
    """Raised when a tool-call span's usage cannot be bound to post-mutation bytes."""


@dataclass(frozen=True)
class ToolCallSpan:
    call_id: str
    tool_name: str
    provider_input_tokens: int
    provider_output_tokens: int
    span_closed_at_turn: int


@dataclass(frozen=True)
class HarnessPayload:
    call_id: str
    post_mutation_bytes: bytes
    mutated_after_span_close: bool
    tokenizer_estimate: int


def reconcile(
    span: ToolCallSpan,
    payload: HarnessPayload,
    tolerance_ratio: float = 0.02,
) -> dict:
    if span.call_id != payload.call_id:
        raise UnreconciledTokenAccounting(
            f"join key mismatch: span={span.call_id} payload={payload.call_id}"
        )

    if not payload.mutated_after_span_close:
        return {
            "call_id": span.call_id,
            "reconciled": True,
            "delta_tokens": 0,
            "payload_digest": hashlib.sha256(payload.post_mutation_bytes).hexdigest(),
        }

    claimed = span.provider_input_tokens + span.provider_output_tokens
    observed = payload.tokenizer_estimate
    delta = observed - claimed
    ratio = abs(delta) / max(claimed, 1)

    if ratio > tolerance_ratio:
        # The span closed before the harness finished rewriting the payload.
        # We cannot trust provider usage as the final word for this call.
        raise UnreconciledTokenAccounting(
            f"call {span.call_id} ({span.tool_name}): claimed={claimed} "
            f"observed={observed} delta={delta} ratio={ratio:.4f} "
            f"exceeds tolerance {tolerance_ratio}"
        )

    return {
        "call_id": span.call_id,
        "reconciled": True,
        "delta_tokens": delta,
        "payload_digest": hashlib.sha256(payload.post_mutation_bytes).hexdigest(),
    }
