# 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-the-actual-token-ledger-when-a-tool-call-event-stream-is-trun.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reconcile-opentelemetry-genai-span-attributes-against-the-actual-token-ledger-when-a-tool-call-event-stream-is-trun.warrant.json
# Markdown SHA-256:   7b52533ed143d44c8d231556f6c91d8fdc79f510169192cef4776c2c2c8a4cd5
# Code AST SHA-256:   d7a70b09e2d9cde1ef1c4f9ec8806a6b32b58037975a6cbfa8ccfbac8c6a23b7
# Verified Classes:   TelemetryReconciliationError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TelemetryReconciliationError(RuntimeError):
    """Raised when a GenAI telemetry projection cannot be reconciled with the token ledger."""


def reconcile_invocation(
    ledger_tokens: int | None,
    parent_output_tokens: int,
    observed_tool_event_tokens: int,
    expected_tool_calls: int,
    observed_tool_events: int,
) -> int:
    """
    Return the authoritative token count for an invocation, or raise if the
    telemetry projection is partial and cannot be trusted for resume/budget.
    """
    if ledger_tokens is None:
        # Cold resume: no ledger. We may only proceed if the event stream is
        # provably complete; otherwise fail closed.
        if observed_tool_events != expected_tool_calls:
            raise TelemetryReconciliationError(
                f"No ledger and truncated event stream: "
                f"{observed_tool_events}/{expected_tool_calls} tool events observed. "
                f"Refusing to resume on a partial projection."
            )
        return parent_output_tokens + observed_tool_event_tokens

    projection = parent_output_tokens + observed_tool_event_tokens

    if observed_tool_events != expected_tool_calls and projection != ledger_tokens:
        # Truncation detected and projection diverges from ledger: telemetry is
        # a lower bound only. Use the ledger; never the projection.
        return ledger_tokens

    if projection > ledger_tokens:
        # Projection claims more than was actually spent: accounting bug or
        # duplicate events. Hard stop.
        raise TelemetryReconciliationError(
            f"Projection {projection} exceeds ledger {ledger_tokens}; "
            f"event stream likely duplicated or misattributed."
        )

    return ledger_tokens
