# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-silent-span-attribute-loss-when-an-opentelemetry-genai-tool-call-event-is-truncated-by-the-batchspanprocessor-queue.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-silent-span-attribute-loss-when-an-opentelemetry-genai-tool-call-event-is-truncated-by-the-batchspanprocessor-queue.warrant.json
# Markdown SHA-256:   20237b36fbc7330a05e8616cbdf63fd43bdd0c170a4493a9dba9d70f1e19a2ff
# Code AST SHA-256:   d8b46f9369a2b4565ac80351b35821d22e08199551bb3f7aad75cb244e96d4c7
# Verified Classes:   TelemetryDropError, TurnRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import logging
from dataclasses import dataclass

log = logging.getLogger("agent.telemetry.reconcile")


class TelemetryDropError(RuntimeError):
    """Raised when exported GenAI child spans do not match the agent action log.

    Distinguishes telemetry loss (BSP tail-drop) from genuine tool-execution
    failure so that token accounting is never silently corrupted.
    """


@dataclass(frozen=True)
class TurnRecord:
    parent_span_id: str
    action_log_tool_calls: int          # authoritative: recorded by the agent
    exported_tool_spans: int            # derived: what the OTel backend received
    parent_output_tokens: int
    sum_child_input_tokens: int


def reconcile_turn(record: TurnRecord, tolerance: float = 0.0) -> None:
    """Enforce the GenAI accounting invariant before the agent commits its budget.

    Invariant: exported child tool spans must equal the agent's own action log.
    A shortfall means the BatchSpanProcessor dropped spans under backpressure;
    the trace is incomplete and must not be used for token accounting.
    """
    if record.exported_tool_spans < record.action_log_tool_calls:
        missing = record.action_log_tool_calls - record.exported_tool_spans
        raise TelemetryDropError(
            f"parent={record.parent_span_id}: {missing} of "
            f"{record.action_log_tool_calls} tool-call spans missing from export; "
            f"BSP queue likely saturated. Re-emit from action log before "
            f"committing token budget."
        )

    if record.exported_tool_spans > record.action_log_tool_calls:
        raise TelemetryDropError(
            f"parent={record.parent_span_id}: export contains "
            f"{record.exported_tool_spans} child spans but action log has "
            f"{record.action_log_tool_calls}; duplicate or foreign spans detected."
        )

    expected = record.parent_output_tokens + record.sum_child_input_tokens
    if expected <= 0:
        raise TelemetryDropError(
            f"parent={record.parent_span_id}: zero token accounting on a "
            f"completed turn; usage attributes were not populated."
        )


def commit_turn_budget(record: TurnRecord) -> int:
    """Return the token cost the agent may charge forward, after reconciliation."""
    reconcile_turn(record)
    log.info(
        "turn %s reconciled: %d tool spans, %d tokens",
        record.parent_span_id,
        record.exported_tool_spans,
        record.parent_output_tokens + record.sum_child_input_tokens,
    )
    return record.parent_output_tokens + record.sum_child_input_tokens
