# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-opentelemetry-genai-span-as-authoritative-evidence-of-tool-execution-rather-than-a-hint.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-opentelemetry-genai-span-as-authoritative-evidence-of-tool-execution-rather-than-a-hint.warrant.json
# Markdown SHA-256:   9a4f6a416aa0baebfea3c52a96d832cd946ed8dd7d6e668611eb7213f751386f
# Code AST SHA-256:   7d7d7c5588e6d2ff49b19f37d531bd08cce2538e1c7230074b765d4fbca0a747
# Verified Classes:   SpanAuthorityViolation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class SpanAuthorityViolation(RuntimeError):
    """Raised when a GenAI tool-call span is used as effect evidence
    without satisfying the effect-coupling invariant."""


def assert_span_is_authoritative(span: dict, tool_contract: dict) -> None:
    """Gate: may this span be used to skip re-execution on resume?

    A span is authoritative only if its terminal status was set by the
    effect-acknowledgment path, not by an invocation wrapper or teardown.
    """
    status = span.get("status.code")
    closed_by = span.get("internal.closed_by")  # emitter must record this

    if closed_by in ("exception_handler", "finally", "context_exit", "defer"):
        raise SpanAuthorityViolation(
            f"span {span.get('gen_ai.tool.call.id')} closed by {closed_by!r}; "
            "terminal status cannot observe tool effect — span is a hint only"
        )

    if status == "OK" and not tool_contract.get("emits_effect_receipt"):
        raise SpanAuthorityViolation(
            f"tool {span.get('gen_ai.tool.name')!r} emits no effect receipt; "
            "OK status encodes 'did not throw', not 'effect landed'"
        )

    if not tool_contract.get("idempotency_key_attr"):
        raise SpanAuthorityViolation(
            f"tool {span.get('gen_ai.tool.name')!r} exposes no idempotency key; "
            "call.id is client-generated and cannot dedupe retries"
        )

    if span.get("gen_ai.tool.aborted"):
        raise SpanAuthorityViolation(
            "span marked aborted; effect state unknown, must re-execute"
        )
