# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-replay-a-genai-trace-non-idempotent-tool-side-effects-and-the-replay-eligibility-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-replay-a-genai-trace-non-idempotent-tool-side-effects-and-the-replay-eligibility-invariant.warrant.json
# Markdown SHA-256:   544d5fa3c89e1b3e0a5756eefb49b7783b17ab766c8cc385fc03b7ee00fd2a4a
# Code AST SHA-256:   6b796a2185300f34f189ceabe1b993291443fa62ea6c15c83988dc15901620ad
# Verified Classes:   ReplayIneligibleError, HarnessMode, ToolSpan, ReplayEligibility
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from enum import Enum
from typing import Iterable


class ReplayIneligibleError(RuntimeError):
    """Raised when a GenAI trajectory is not sound to replay deterministically."""


class HarnessMode(str, Enum):
    SUBSTITUTE = "substitute"   # sound: recorded outputs fed back
    REINVOKE = "reinvoke"       # unsound: tool bodies re-executed


@dataclass(frozen=True)
class ToolSpan:
    name: str
    span_id: str
    has_result: bool          # gen_ai.tool.call.result present
    has_error: bool           # gen_ai.tool.call.error present
    is_retry_of: str | None   # span_id of the error span this retries, if any
    idempotent_declared: bool # gen_ai.tool.call.idempotent == true


@dataclass(frozen=True)
class ReplayEligibility:
    eligible: bool
    reason: str
    truncate_at: str | None = None  # span_id to truncate before, if partial


def check_replay_eligibility(
    branch: Iterable[ToolSpan],
    mode: HarnessMode,
    counterfactual_asks_current_tool_state: bool,
) -> ReplayEligibility:
    """
    Enforce the Replay-Eligibility Invariant (REI) over a counterfactual branch.

    Returns an eligibility verdict. Raises ReplayIneligibleError only for the
    hard-fail cases (mode violation, missing substitution payload on a span
    that cannot be truncated). Partial eligibility is returned, not raised,
    so the caller can decide to truncate.
    """
    if mode is not HarnessMode.SUBSTITUTE:
        raise ReplayIneligibleError(
            f"harness mode is {mode.value!r}; deterministic replay requires "
            f"'substitute' (re-invoking tool bodies is re-simulation, not replay)"
        )

    if counterfactual_asks_current_tool_state:
        raise ReplayIneligibleError(
            "counterfactual asks 'what would the tool return now'; this is "
            "simulation and requires environment forking, not trace replay"
        )

    spans = list(branch)
    by_id = {s.span_id: s for s in spans}

    # Retry-pair completeness: a retry span without its error span loses the
    # agent's observation of the failure and corrupts causal state.
    for s in spans:
        if s.is_retry_of is not None and s.is_retry_of not in by_id:
            raise ReplayIneligibleError(
                f"retry span {s.span_id} ({s.name}) references missing error "
                f"span {s.is_retry_of}; trajectory is causally incomplete"
            )

    # Substitution payload check. First missing payload truncates the branch
    # at the *predecessor* of the offending span.
    for s in spans:
        if not (s.has_result or s.has_error):
            if s.idempotent_declared:
                # Declared idempotent + no payload: still unsound to reinvoke
                # without explicit opt-in, but we can truncate conservatively.
                return ReplayEligibility(
                    eligible=False,
                    reason=(
                        f"span {s.span_id} ({s.name}) is declared idempotent but "
                        f"carries no recorded output; truncating to avoid "
                        f"re-execution divergence"
                    ),
                    truncate_at=s.span_id,
                )
            return ReplayEligibility(
                eligible=False,
                reason=(
                    f"span {s.span_id} ({s.name}) has no substitutable output "
                    f"(neither gen_ai.tool.call.result nor gen_ai.tool.call.error) "
                    f"and is not declared idempotent; branch is unreplayable past "
                    f"this point"
                ),
                truncate_at=s.span_id,
            )

    return ReplayEligibility(
        eligible=True,
        reason=f"all {len(spans)} tool spans carry substitutable outputs",
    )


def replay_trajectory(branch: list[ToolSpan], mode: HarnessMode) -> list[str]:
    """
    Replay a trajectory, emitting replayed chat-span labels. Refuses to emit
    any span past a truncation point.
    """
    verdict = check_replay_eligibility(
        branch,
        mode=mode,
        counterfactual_asks_current_tool_state=False,
    )
    if not verdict.eligible and verdict.truncate_at is None:
        raise ReplayIneligibleError(verdict.reason)

    emitted: list[str] = []
    for s in branch:
        if verdict.truncate_at is not None and s.span_id == verdict.truncate_at:
            break
        emitted.append(f"replayed:{s.name}")
    return emitted


if __name__ == "__main__":
    # The observed trajectory: issue_refund has no recorded output and is not
    # declared idempotent. Replay must truncate before it.
    observed = [
        ToolSpan("lookup_order", "s1", True, False, None, False),
        ToolSpan("check_refund_policy", "s2", True, False, None, False),
        ToolSpan("issue_refund", "s3", False, False, None, False),  # <-- gap
        ToolSpan("send_confirmation", "s4", False, True, None, False),
        ToolSpan("send_confirmation", "s5", True, False, "s4", False),
    ]
    try:
        replay_trajectory(observed, HarnessMode.REINVOKE)
    except ReplayIneligibleError as e:
        print(f"refused: {e}")

    verdict = check_replay_eligibility(observed, HarnessMode.SUBSTITUTE, False)
    print(f"verdict: eligible={verdict.eligible} truncate_at={verdict.truncate_at}")
    print(f"reason: {verdict.reason}")
