# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-genai-agent-span-because-the-token-count-attribute-and-the-child-tool-call-spans-disagree-at-export-time.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-genai-agent-span-because-the-token-count-attribute-and-the-child-tool-call-spans-disagree-at-export-time.warrant.json
# Markdown SHA-256:   1d813bd3ac1e8bf826262f34b98a84212a308ebccf28af39c538c893baf7ae57
# Code AST SHA-256:   179ece2a1cd8a0275766945748182db4559c227479d621bad53c6fcb3cd25c93
# Verified Classes:   TokenAccountingMismatchError, SpanUsage
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class TokenAccountingMismatchError(RuntimeError):
    """Raised when a parent agent span's token attributes cannot be safely reconciled
    with the sum of its child span usage without erasing evidence of unrecorded
    consumption (retries, shadow calls, compaction)."""


@dataclass
class SpanUsage:
    span_id: str
    input_tokens: int
    output_tokens: int
    is_child: bool


def reconcile_agent_span(
    parent: SpanUsage,
    children: list[SpanUsage],
    compaction_threshold_tokens: int = 4000,
    double_emit_factor: float = 2.0,
) -> dict:
    """Decide whether a parent agent span may be exported as-is, flagged, or refused.

    Returns a dict describing the export decision. Raises TokenAccountingMismatchError
    when the mismatch indicates a defect that must not be exported as a clean trace.
    """
    if not children:
        # No independent measurement: the invariant is undefined, export as partial.
        return {"action": "export_partial", "reason": "no_child_usage", "delta": None}

    child_in = sum(c.input_tokens for c in children)
    child_out = sum(c.output_tokens for c in children)
    delta_in = child_in - parent.input_tokens
    delta_out = child_out - parent.output_tokens

    # Instrumentation defect: children likely emitted twice under at-least-once export.
    if child_in > parent.input_tokens * double_emit_factor and parent.input_tokens > 0:
        raise TokenAccountingMismatchError(
            f"parent span {parent.span_id} reports {parent.input_tokens} input tokens "
            f"but children sum to {child_in} ({child_in / parent.input_tokens:.1f}x). "
            f"Likely duplicate child emission; refusing to export a poisoned trace."
        )

    if delta_in > 0 or delta_out > 0:
        # Unrecorded consumption: retry, shadow call, or missed child. Preserve the gap.
        return {
            "action": "export_with_mismatch_event",
            "event": "gen_ai.accounting.mismatch",
            "delta_input": delta_in,
            "delta_output": delta_out,
            "child_span_ids": [c.span_id for c in children],
        }

    if -delta_in > compaction_threshold_tokens:
        # Structural under-report, typically context compaction or final-chunk-only usage.
        return {
            "action": "export_partial",
            "reason": "compaction_or_streaming_underreport",
            "delta_input": delta_in,
        }

    return {"action": "export_clean", "delta_input": delta_in, "delta_output": delta_out}
