# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-opentelemetry-genai-span-boundaries-as-lossy-attribution-contracts-rather-than-faithful-execution-records.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-opentelemetry-genai-span-boundaries-as-lossy-attribution-contracts-rather-than-faithful-execution-records.warrant.json
# Markdown SHA-256:   4f2fce9c7febe679879fdbee194d8be3f9d69aa109d2bfe6e9449304d5dbfa95
# Code AST SHA-256:   1891e2ab53d76a82cbde51229cdcec6cbc589bf899200b76c1fe6334e48ca106
# Verified Classes:   AttributionContractViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class AttributionContractViolation(RuntimeError):
    """Raised when span-derived usage cannot be trusted as an attribution source."""


def reconcile_turn_usage(
    span_usage: dict,
    ledger_usage: dict | None,
    *,
    retry_count: int,
    concurrent_tool_fanout: bool,
    crossed_checkpoint: bool,
    distinct_instances: int,
    retry_rate_threshold: float = 0.01,
) -> dict:
    """
    Decide whether span usage is authoritative for a turn, or whether the
    ledger must override it. Returns the usage the reconciler should bill.
    """
    span_total = span_usage.get("input_tokens", 0) + span_usage.get("output_tokens", 0)

    # Boundary conditions under which the span tree is a lossy projection.
    lossy = (
        retry_count > 0
        or concurrent_tool_fanout
        or crossed_checkpoint
        or distinct_instances > 1
    )

    if not lossy:
        # Span tree is within noise; it is the contract.
        return span_usage

    if ledger_usage is None:
        # Lossy boundary and no independent ledger: refuse to bill from spans.
        raise AttributionContractViolation(
            f"span usage ({span_total} tokens) is non-authoritative under "
            f"retry={retry_count}, fanout={concurrent_tool_fanout}, "
            f"checkpoint={crossed_checkpoint}, instances={distinct_instances}; "
            "no ledger row to reconcile against"
        )

    ledger_total = ledger_usage.get("input_tokens", 0) + ledger_usage.get("output_tokens", 0)

    # Divergence beyond a tolerance means the span tree double-counted or dropped.
    if span_total > 0 and abs(span_total - ledger_total) / max(span_total, 1) > 0.05:
        # Ledger wins; span is advisory only.
        return ledger_usage

    return ledger_usage


def commit_turn(agent_state, turn_index: int, provider_response: dict) -> None:
    """
    Executing agent must commit the authoritative ledger row BEFORE closing
    the gen_ai.chat span, so the reconciler always has a reference.
    """
    if "usage" not in provider_response:
        raise AttributionContractViolation(
            f"turn {turn_index}: provider response carries no usage; "
            "cannot commit ledger row, span usage would be the only source"
        )
    agent_state.ledger.append(
        {
            "turn_index": turn_index,
            "input_tokens": provider_response["usage"]["input_tokens"],
            "output_tokens": provider_response["usage"]["output_tokens"],
            "request_id": provider_response.get("id"),
        }
    )
