# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-token-accounting-fidelity-when-otel-genai-spans-are-re-parented-across-an-agent-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-token-accounting-fidelity-when-otel-genai-spans-are-re-parented-across-an-agent-handoff.warrant.json
# Markdown SHA-256:   247d373ab16dea73566ee804ef397e97bb1dfbd6fb362d592351a3241d1653bd
# Code AST SHA-256:   b0675477fa20d27963329cdc57040621457145bd3f4a571265b1bfbfaf6c262f
# Verified Classes:   TokenAccountingDivergence, HandoffUsage
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class TokenAccountingDivergence(RuntimeError):
    """Raised when a delegated sub-agent's self-reported token usage does not
    reconcile with the parent's trace-attributed aggregate."""
    pass


@dataclass
class HandoffUsage:
    input_tokens: int
    output_tokens: int
    trace_id: str | None  # None if the child failed to join the parent trace
    operation_name: str   # must be "chat" for tokens to be counted


def reconcile_handoff(
    parent_aggregate_input: int,
    parent_aggregate_output: int,
    child_usage: HandoffUsage,
    tolerance_ratio: float = 0.02,
) -> int:
    """
    Reconcile a completed sub-agent handoff against the parent's token aggregate.
    Returns the corrected total input tokens. Raises on any divergence that
    indicates span fragmentation or mislabeled operation spans.
    """
    if child_usage.trace_id is None:
        raise TokenAccountingDivergence(
            "child spans did not join parent trace_id; parent aggregate is "
            "structurally unable to include delegated tokens"
        )

    if child_usage.operation_name != "chat":
        raise TokenAccountingDivergence(
            f"child recorded usage on operation '{child_usage.operation_name}', "
            "not 'chat'; aggregators filtering by operation name will drop it"
        )

    expected_input = parent_aggregate_input + child_usage.input_tokens
    expected_output = parent_aggregate_output + child_usage.output_tokens

    # The parent aggregate should already include the child if propagation held.
    # If it does not, the delta is the delegation gap.
    gap_input = expected_input - parent_aggregate_input
    if child_usage.input_tokens > 0 and gap_input / child_usage.input_tokens > 1.0 - tolerance_ratio:
        raise TokenAccountingDivergence(
            f"parent aggregate ({parent_aggregate_input}) does not reflect "
            f"child input tokens ({child_usage.input_tokens}); "
            "delegated work is invisible to trace-based budget guards"
        )

    return expected_input
