# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-causal-trace-divergence-when-a-tool-s-side-effect-commits-before-its-span-closes.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-causal-trace-divergence-when-a-tool-s-side-effect-commits-before-its-span-closes.warrant.json
# Markdown SHA-256:   ab0bd1e0cbe7ce08ac01d75b6157bbd7f45e247cf045413b41784d32869cdd69
# Code AST SHA-256:   e604f6422ed637f771b27e0f230ab8a15172e0f5de658f7104495494d1f5123a
# Verified Classes:   OrphanedEffectSpanError, Span, Receipt
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class OrphanedEffectSpanError(RuntimeError):
    """Raised when an effectful tool-call span is orphaned and the effect
    authority cannot confirm whether the effect committed. Retrying in this
    state is unsafe: it risks double-commit. The caller must escalate to the
    effect authority's reconciliation path."""
    pass


@dataclass(frozen=True)
class Span:
    span_id: str
    tool_name: str
    idempotency_key: str
    closed: bool
    effectful: bool


@dataclass(frozen=True)
class Receipt:
    idempotency_key: str
    committed: bool
    receipt_hash: str


def derive_idempotency_key(tool_name: str, invoice_id: str, amount_cents: int, run_id: str) -> str:
    # Stable across retries: derived from inputs, NOT from a per-call UUID.
    material = f"{tool_name}|{invoice_id}|{amount_cents}|{run_id}".encode()
    return hashlib.sha256(material).hexdigest()


def resolve_orphan(span: Span, lookup) -> Receipt:
    """Given an orphaned effectful span, determine whether the effect committed.

    The trace is NOT consulted for the answer — only the effect authority is.
    """
    if not span.effectful:
        # Read-only tools are safe to re-emit; no reconciliation needed.
        return Receipt(idempotency_key=span.idempotency_key, committed=False, receipt_hash="")

    if span.closed:
        raise OrphanedEffectSpanError(
            f"span {span.span_id} is closed; resolve_orphan is only for orphans"
        )

    receipt: Optional[Receipt] = lookup(span.tool_name, span.idempotency_key)

    if receipt is None:
        # Authority has no record. The effect may still be in flight at the
        # authority, or the authority may have lost the write. We cannot
        # distinguish, and re-emitting risks double-commit if the first
        # write lands after our lookup. Escalate rather than guess.
        raise OrphanedEffectSpanError(
            f"effect authority has no receipt for {span.tool_name} "
            f"key={span.idempotency_key}; effect state unknown, cannot safely retry"
        )

    return receipt


def safe_retry(span: Span, lookup, re_emit) -> Receipt:
    receipt = resolve_orphan(span, lookup)
    if receipt.committed:
        # Effect already landed. Do NOT re-emit. Reconcile the trace instead.
        return receipt
    # Authority confirms no commit for this key; re-emit with the SAME key.
    return re_emit(span.tool_name, span.idempotency_key)


def reconcile(span: Span, lookup) -> Span:
    """Patch an orphaned span with a synthetic result when the effect committed."""
    receipt = resolve_orphan(span, lookup)
    if not receipt.committed:
        raise OrphanedEffectSpanError(
            f"cannot reconcile span {span.span_id}: effect never committed"
        )
    return Span(
        span_id=span.span_id,
        tool_name=span.tool_name,
        idempotency_key=span.idempotency_key,
        closed=True,
        effectful=span.effectful,
    )
