# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-emit-gen-ai-tool-call-id-lineage-when-token-attribution-crosses-a-compaction-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-emit-gen-ai-tool-call-id-lineage-when-token-attribution-crosses-a-compaction-boundary.warrant.json
# Markdown SHA-256:   d74c7fb97ea8f10bcbfe70d3ab602b6821887be83569592abdc3079e0345185f
# Code AST SHA-256:   e7904d0a47c98bb09bdd4000cf4316290eee7d5e925aa305f3c3ae1d50edab37
# Verified Classes:   LineageAttributionError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class LineageAttributionError(RuntimeError):
    """Raised when a GenAI span attempts to claim tool-call lineage over
    tokens that were not contributed by that call's own prompt."""
    pass


def emit_tool_call_span(
    tool_call_id: str,
    total_input_tokens: int,
    fresh_input_tokens: int,
    replayed_input_tokens: int,
    tokenizer_tolerance: int = 3,
) -> dict:
    """Build the gen_ai.* attribute dict for a tool-call span.

    Enforces the invariant: a span may carry gen_ai.tool.call.id only if
    every input token it reports was contributed by this call's prompt.
    """
    if fresh_input_tokens + replayed_input_tokens != total_input_tokens:
        raise LineageAttributionError(
            f"usage partition does not sum: fresh={fresh_input_tokens} "
            f"replayed={replayed_input_tokens} total={total_input_tokens}"
        )

    attrs = {
        "gen_ai.usage.input_tokens": total_input_tokens,
        "gen_ai.usage.fresh_input_tokens": fresh_input_tokens,
        "gen_ai.usage.replayed_input_tokens": replayed_input_tokens,
    }

    contaminated = replayed_input_tokens > tokenizer_tolerance
    if contaminated:
        # Lineage is ambiguous: refuse to re-parent replayed tokens.
        attrs["genai.lineage.ambiguous"] = True
        if fresh_input_tokens == 0:
            raise LineageAttributionError(
                f"span for {tool_call_id} is entirely replayed tokens; "
                "no legitimate tool.call.id can be claimed"
            )
        # Scope lineage to the fresh partition only, explicitly partitioned.
        attrs["gen_ai.tool.call.id"] = tool_call_id
        attrs["genai.attribution.scope"] = "fresh_partition_only"
    else:
        attrs["gen_ai.tool.call.id"] = tool_call_id
        attrs["genai.attribution.scope"] = "full_span"

    return attrs


def reconcile_trace_cost(spans: list[dict]) -> int:
    """Sum per-call input tokens and assert it matches per-span totals
    minus explicitly-marked replayed tokens."""
    per_call = 0
    per_span = 0
    replayed = 0
    for s in spans:
        per_span += s.get("gen_ai.usage.input_tokens", 0)
        replayed += s.get("gen_ai.usage.replayed_input_tokens", 0)
        if "gen_ai.tool.call.id" in s:
            scope = s.get("genai.attribution.scope")
            if scope == "fresh_partition_only":
                per_call += s.get("gen_ai.usage.fresh_input_tokens", 0)
            elif scope == "full_span":
                per_call += s.get("gen_ai.usage.input_tokens", 0)
            else:
                raise LineageAttributionError(
                    f"span claims tool.call.id without attribution scope: {s}"
                )
    if per_call != per_span - replayed:
        raise LineageAttributionError(
            f"cost ledger drifted: per_call={per_call} "
            f"per_span={per_span} replayed={replayed}"
        )
    return per_call
