# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-terminal-agent-span-the-opentelemetry-genai-parent-span-completeness-invariant-under-mid-tool-call-token-budget.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-terminal-agent-span-the-opentelemetry-genai-parent-span-completeness-invariant-under-mid-tool-call-token-budget.warrant.json
# Markdown SHA-256:   7d4984f24f4389bc486fd10ede5d172a3002882ee7f1bd913b5e458845652d20
# Code AST SHA-256:   a1e69279403c34164dd1b138ae036ff91ed3d6424a406268ff22af4bcf789f89
# Verified Classes:   UnaccountedSpendOnOkSpan, AgentSpan
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UnaccountedSpendOnOkSpan(RuntimeError):
    """Raised when a parent agent span would terminate OK despite irreversible token spend."""
    pass


@dataclass
class AgentSpan:
    name: str
    status: str = "UNSET"
    usage_output_tokens: int = 0
    abandoned: bool = False
    open_children: list = field(default_factory=list)


def teardown_parent_span(
    span: AgentSpan,
    *,
    turn_response_received: bool,
    tokens_billed_this_turn: int,
    child_spans: list,
) -> AgentSpan:
    """Close a parent invoke_agent span under the parent-completeness invariant."""
    still_open = [c for c in child_spans if c.status in ("UNSET", "OK_PENDING")]
    if still_open:
        # Children bound the parent's terminal state below.
        span.status = "ERROR"
        span.abandoned = True
        span.usage_output_tokens = tokens_billed_this_turn
        return span

    if turn_response_received and tokens_billed_this_turn > 0:
        # Irreversible spend occurred; the span must carry it and not claim OK.
        span.status = "ERROR"
        span.abandoned = True
        span.usage_output_tokens = tokens_billed_this_turn
        return span

    if span.status == "OK" and span.usage_output_tokens == 0 and tokens_billed_this_turn > 0:
        raise UnaccountedSpendOnOkSpan(
            f"span {span.name!r} would end OK with {tokens_billed_this_turn} "
            f"billed tokens unaccounted; refusing teardown"
        )

    span.status = "OK"
    span.usage_output_tokens = tokens_billed_this_turn
    return span
