# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-an-opentelemetry-genai-span-as-authoritative-for-tool-call-state-and-when-must-it-re-derive-from-the-tool-ledger.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-an-opentelemetry-genai-span-as-authoritative-for-tool-call-state-and-when-must-it-re-derive-from-the-tool-ledger.warrant.json
# Markdown SHA-256:   4fab17f1eb4c3d7242c008bb79912e997c12e4f41888160ac6a5c2c5950a9254
# Code AST SHA-256:   14a5231875381d950213106fddad52fa680598f5c28bb22dbdb327e217ec6c79
# Verified Classes:   SpanAuthorityError, SpanStatus, GenAIToolSpan, LedgerEntry, ResumeDecision
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from enum import Enum
from typing import Optional


class SpanAuthorityError(RuntimeError):
    """Raised when a GenAI span is used as proof of effect it cannot support."""


class SpanStatus(str, Enum):
    OK = "OK"
    ERROR = "ERROR"


@dataclass(frozen=True)
class GenAIToolSpan:
    call_id: str
    tool_name: str
    status: SpanStatus
    commit_id: Optional[str]  # attribute carrying durable-commit token, if any


@dataclass(frozen=True)
class LedgerEntry:
    commit_id: str
    call_id: str
    tool_name: str


class ResumeDecision(str, Enum):
    SKIP = "skip"            # span + ledger agree; effect durable
    RE_DERIVE = "re_derive"  # span claims OK but no commit; reconcile via idempotent read
    RE_EXECUTE = "re_execute"  # no span; unknown -> idempotent re-execute
    TRUST_LEDGER = "trust_ledger"  # span ERROR but ledger committed; superseded attempt


def reconcile(
    span: Optional[GenAIToolSpan],
    ledger: dict[str, LedgerEntry],
    checkpoint_in_flight: bool,
) -> ResumeDecision:
    if span is None:
        if not checkpoint_in_flight:
            raise SpanAuthorityError(
                "no span and no in-flight checkpoint: cannot classify call state"
            )
        return ResumeDecision.RE_EXECUTE

    if span.status is SpanStatus.ERROR:
        if span.commit_id and span.commit_id in ledger:
            return ResumeDecision.TRUST_LEDGER
        return ResumeDecision.RE_EXECUTE

    # span.status is OK: necessary but not sufficient for SKIP
    if span.commit_id is None:
        # orphan span: telemetry-only success, effect unproven
        return ResumeDecision.RE_DERIVE
    entry = ledger.get(span.commit_id)
    if entry is None or entry.call_id != span.call_id:
        return ResumeDecision.RE_DERIVE
    return ResumeDecision.SKIP


def assert_skippable(span: GenAIToolSpan, ledger: dict[str, LedgerEntry]) -> None:
    decision = reconcile(span, ledger, checkpoint_in_flight=True)
    if decision is not ResumeDecision.SKIP:
        raise SpanAuthorityError(
            f"refusing to skip tool {span.tool_name!r} call {span.call_id!r}: "
            f"span claims OK but reconciliation yielded {decision.value}"
        )
