# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-opentelemetry-genai-span-attributes-as-authoritative-state-rather-than-telemetry.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-opentelemetry-genai-span-attributes-as-authoritative-state-rather-than-telemetry.warrant.json
# Markdown SHA-256:   72d2379a53e2363f1e14d1f214caffc997e8f40029db0c057c750944739e000d
# Code AST SHA-256:   bd1c98bce3634732e14fdea5bdf6982b8be00c41de40711d8332f2154983ff2c
# Verified Classes:   SpanStateAuthorityError, GenAISpan
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class SpanStateAuthorityError(RuntimeError):
    """Raised when a GenAI span is used as authoritative state without meeting the closure/attestation invariant."""


@dataclass
class GenAISpan:
    span_id: str
    status_code: str                 # "OK" | "ERROR" | "UNSET"
    end_time: Optional[float]        # None => still open / process died
    finish_reasons: list[str]        # raw, unnormalized
    agent_effect_id: Optional[str]   # agent-authored, post-side-effect
    child_span_ids: list[str]
    children_terminal: bool


def assert_span_authoritative(span: GenAISpan, dedup_ledger: set[str]) -> str:
    """
    Gate a resume decision on the span-authority invariant.
    Returns the effect_id to dedup against if the span is authoritative.
    """
    if span.end_time is None or span.status_code == "UNSET":
        raise SpanStateAuthorityError(
            f"span {span.span_id} is not closure-complete "
            f"(status={span.status_code}, end_time={span.end_time}); "
            "treat as evidence, resume from checkpoint store"
        )

    if not span.children_terminal:
        raise SpanStateAuthorityError(
            f"span {span.span_id} has dangling child spans {span.child_span_ids}; "
            "parent cannot attest to child side effects"
        )

    if "length" in span.finish_reasons and span.agent_effect_id is None:
        raise SpanStateAuthorityError(
            f"span {span.span_id} terminated on max_tokens with no agent effect attestation; "
            "generation was truncated, tool payload may be incomplete"
        )

    if span.agent_effect_id is None:
        raise SpanStateAuthorityError(
            f"span {span.span_id} carries only provider-authored attributes; "
            "provider telemetry cannot attest to agent-side commits"
        )

    if span.agent_effect_id in dedup_ledger:
        raise SpanStateAuthorityError(
            f"effect {span.agent_effect_id} already applied; "
            "replay would double-apply side effect — skip re-execution"
        )

    return span.agent_effect_id
