# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reconcile-opentelemetry-genai-span-accounting-against-the-tool-call-fan-out-it-actually-executed-rather-than-trusti.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reconcile-opentelemetry-genai-span-accounting-against-the-tool-call-fan-out-it-actually-executed-rather-than-trusti.warrant.json
# Markdown SHA-256:   2b2602a84bfc30ec70dc10964872b514808daca07198699e197d0bd77411826f
# Code AST SHA-256:   91363cfd2c0eae73c7c7b262762f17673d39c6021a178db2dcaed8d8986e03fe
# Verified Classes:   GenAiSpanReconciliationError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class GenAiSpanReconciliationError(RuntimeError):
    """Raised when a trace's GenAI span token accounting cannot certify
    that the agent actually observed its tool results."""

# Tokenizer-ratio tolerance: observed input growth may fall below
# (prior output + tool result tokens) by at most this fraction before
# we declare silent truncation.
TRUNCATION_TOLERANCE = 0.15


def reconcile_turn_deltas(chat_spans: list[dict], tool_results: dict[str, int]) -> None:
    """
    chat_spans: ordered list of dicts with keys
        'gen_ai.usage.input_tokens', 'gen_ai.usage.output_tokens',
        'tool_call_ids' (list of gen_ai.tool.call.id emitted by this turn)
    tool_results: map gen_ai.tool.call.id -> token count of the tool result
        injected before the NEXT chat turn.

    Raises GenAiSpanReconciliationError if any turn's input growth is
    inconsistent with the prior turn's output plus intervening tool results.
    """
    for i in range(1, len(chat_spans)):
        prev = chat_spans[i - 1]
        cur = chat_spans[i]

        tool_tokens = sum(tool_results.get(cid, 0) for cid in prev["tool_call_ids"])
        expected_growth = prev["gen_ai.usage.output_tokens"] + tool_tokens
        observed_growth = (
            cur["gen_ai.usage.input_tokens"] - prev["gen_ai.usage.input_tokens"]
        )

        if expected_growth == 0:
            continue

        shortfall_ratio = (expected_growth - observed_growth) / expected_growth
        if shortfall_ratio > TRUNCATION_TOLERANCE:
            raise GenAiSpanReconciliationError(
                f"Turn {i}: expected input growth ~{expected_growth} tokens "
                f"(prior output {prev['gen_ai.usage.output_tokens']} + "
                f"{tool_tokens} tool-result tokens) but observed only "
                f"{observed_growth}. Shortfall {shortfall_ratio:.0%} exceeds "
                f"tolerance {TRUNCATION_TOLERANCE:.0%}; agent likely answered "
                f"from stale context. Tool call ids in prior turn: "
                f"{prev['tool_call_ids']}."
            )


def certify_run(chat_spans: list[dict], tool_results: dict[str, int],
                context_limit: int) -> bool:
    if not chat_spans:
        raise GenAiSpanReconciliationError("Empty trace: no gen_ai.chat spans.")
    reconcile_turn_deltas(chat_spans, tool_results)
    tail_input = chat_spans[-1]["gen_ai.usage.input_tokens"]
    if tail_input > 0.80 * context_limit:
        raise GenAiSpanReconciliationError(
            f"Final-turn input {tail_input} exceeds 80% of context limit "
            f"{context_limit}; mean-based health check would mask this tail."
        )
    return True
