# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-emit-a-genai-span-when-tool-call-attributes-cannot-be-reconciled-with-the-parent-token-budget.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-emit-a-genai-span-when-tool-call-attributes-cannot-be-reconciled-with-the-parent-token-budget.warrant.json
# Markdown SHA-256:   f04128a621810dd45843616d56a99ad22827295157a3efc336f533e2961a784a
# Code AST SHA-256:   144a372437483667b8ddbcd938a7419951e6af6d501442abf2126d3ab7a4664b
# Verified Classes:   UnreconciledUsageError, SpanUsage, ToolSpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class UnreconciledUsageError(RuntimeError):
    """Raised when a child tool span would report usage that may overlap the parent's."""


@dataclass
class SpanUsage:
    input_tokens: int = 0
    output_tokens: int = 0


@dataclass
class ToolSpan:
    name: str
    usage: SpanUsage | None


def emit_tool_span(
    tool_name: str,
    child_usage: SpanUsage | None,
    parent_output_tokens: int,
    ownership_committed: bool,
) -> ToolSpan:
    if child_usage is not None and child_usage.input_tokens > 0:
        if not ownership_committed:
            raise UnreconciledUsageError(
                f"tool span {tool_name!r} reports {child_usage.input_tokens} input "
                f"tokens but no accounting-ownership convention is committed; "
                f"parent already reported {parent_output_tokens} output tokens and "
                f"overlap cannot be ruled out. Refusing to emit usage attributes."
            )
        if child_usage.input_tokens > parent_output_tokens:
            raise UnreconciledUsageError(
                f"tool span {tool_name!r} input_tokens={child_usage.input_tokens} "
                f"exceeds parent output_tokens={parent_output_tokens}; argument "
                f"echo cannot be bounded by the parent's generated payload."
            )
    return ToolSpan(name=tool_name, usage=child_usage)


def safe_emit(tool_name, child_usage, parent_output_tokens, ownership_committed):
    try:
        return emit_tool_span(tool_name, child_usage, parent_output_tokens, ownership_committed)
    except UnreconciledUsageError:
        # Emit the span with usage stripped; tree integrity preserved, cost falls back to root.
        return ToolSpan(name=tool_name, usage=None)
