# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-genai-span-whose-token-accounting-attributes-were-inherited-across-a-tool-call-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-genai-span-whose-token-accounting-attributes-were-inherited-across-a-tool-call-boundary.warrant.json
# Markdown SHA-256:   17a61b787774a871ea79e7cfe12176cbbeefe6e643eef03720a56461d0ca6dd3
# Code AST SHA-256:   8f6ddb049fbfd3d3e99a0d58bece8a3305e88bb339e386c714ba0498d6789950
# Verified Classes:   InheritedUsageError, FabricatedUsageError, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Optional

MODEL_OPS = frozenset({"chat", "text_completion", "generate_content"})
TOOL_OP = "execute_tool"
USAGE_KEYS = ("gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens")
SOURCE_KEY = "gen_ai.usage.source"
MEASURED = "measured"


class InheritedUsageError(RuntimeError):
    """Raised when a tool span's usage attributes were inherited from a model ancestor."""


class FabricatedUsageError(RuntimeError):
    """Raised when a non-model tool span carries usage it cannot attribute to a measurement."""


@dataclass
class Span:
    name: str
    operation: str
    attributes: dict
    parent: Optional["Span"] = None

    def get(self, key: str):
        return self.attributes.get(key)


def _nearest_model_ancestor(span: Span) -> Optional[Span]:
    node = span.parent
    while node is not None:
        if node.get("gen_ai.operation.name") in MODEL_OPS:
            return node
        node = node.parent
    return None


def validate_usage_provenance(span: Span) -> Optional[str]:
    """
    Returns None if the span's usage attributes are valid.
    Raises InheritedUsageError / FabricatedUsageError otherwise.
    Stripping is the caller's responsibility; this function only decides.
    """
    if span.get("gen_ai.operation.name") != TOOL_OP:
        return None

    usage_present = [k for k in USAGE_KEYS if span.get(k) is not None]
    if not usage_present:
        return None

    ancestor = _nearest_model_ancestor(span)
    measured = span.get(SOURCE_KEY) == MEASURED

    if ancestor is None:
        if measured:
            return None
        raise FabricatedUsageError(
            f"tool span {span.name!r} carries {usage_present} with no model ancestor "
            f"and no {SOURCE_KEY}={MEASURED!r} marker"
        )

    identical = all(
        span.get(k) is not None and span.get(k) == ancestor.get(k) for k in USAGE_KEYS
    )

    if identical and not measured:
        raise InheritedUsageError(
            f"tool span {span.name!r} inherited {usage_present} from ancestor "
            f"{ancestor.name!r} (values {ancestor.get(USAGE_KEYS[0])}/"
            f"{ancestor.get(USAGE_KEYS[1])}); no measured marker present"
        )

    if not identical and not measured:
        raise FabricatedUsageError(
            f"tool span {span.name!r} has usage {usage_present} that differs from "
            f"ancestor {ancestor.name!r} but is not marked measured"
        )

    return None


def process_span(span: Span) -> Span:
    """Strip inherited/fabricated usage, emit the (structurally intact) span."""
    try:
        validate_usage_provenance(span)
        return span
    except (InheritedUsageError, FabricatedUsageError):
        for k in USAGE_KEYS:
            span.attributes.pop(k, None)
        span.attributes["genai.usage.rejected"] = "inherited_or_unattributed"
        return span


# --- exercise ---
if __name__ == "__main__":
    parent = Span("chat gpt-4o", "chat", {
        "gen_ai.usage.input_tokens": 1842,
        "gen_ai.usage.output_tokens": 210,
    })
    tool = Span("execute_tool search", TOOL_OP, {
        "gen_ai.tool.name": "search",
        "gen_ai.usage.input_tokens": 1842,
        "gen_ai.usage.output_tokens": 210,
    }, parent=parent)

    try:
        validate_usage_provenance(tool)
    except InheritedUsageError as e:
        print(f"REJECT: {e}")

    cleaned = process_span(tool)
    assert "gen_ai.usage.output_tokens" not in cleaned.attributes
    print(cleaned.attributes)
