# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-the-counterfactual-fan-out-of-an-observability-replay-trace-when-tool-call-side-effects-are-non-idempotent.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-the-counterfactual-fan-out-of-an-observability-replay-trace-when-tool-call-side-effects-are-non-idempotent.warrant.json
# Markdown SHA-256:   c7a4b185582b514c21768c986828ce9ea6017e076425931b4562e572d42774e3
# Code AST SHA-256:   531e6f5dbc8171ca3f6fe334080c05665d41071e0cd46afce6b190d3124eb773
# Verified Classes:   EffectClass, CounterfactualForkError, ToolCall
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class EffectClass(Enum):
    IDEMPOTENT = "idempotent"
    REVERSIBLE = "reversible"          # has a registered compensator
    IRREVERSIBLE = "irreversible"


class CounterfactualForkError(RuntimeError):
    """Raised when a replay fork is requested at a step whose downstream
    span contains effects that cannot be replayed or compensated."""


@dataclass(frozen=True)
class ToolCall:
    step: int
    name: str
    effect: EffectClass
    has_compensator: bool = False


def assert_forkable(trace: list[ToolCall], fork_step: int) -> None:
    """Enforce: a fork at `fork_step` is valid only if every downstream
    non-idempotent call is reversible via a registered compensator.
    Otherwise the recorded observations past the first blocking call are
    unreachable from the forked state and must not be replayed verbatim."""
    downstream = [c for c in trace if c.step >= fork_step]
    for call in downstream:
        if call.effect is EffectClass.IRREVERSIBLE:
            raise CounterfactualForkError(
                f"fork at step {fork_step} invalid: step {call.step} "
                f"({call.name}) is irreversible; downstream observations "
                f"are not reachable from the forked state. Reproduce the "
                f"environment instead of replaying the trace."
            )
        if call.effect is EffectClass.REVERSIBLE and not call.has_compensator:
            raise CounterfactualForkError(
                f"fork at step {fork_step} invalid: step {call.step} "
                f"({call.name}) is reversible but no compensator is "
                f"registered; side effects would leak into sibling replays."
            )


# Observed trajectory: create_branch then push, both non-idempotent.
trace = [
    ToolCall(step=7, name="create_branch", effect=EffectClass.REVERSIBLE,
             has_compensator=False),
    ToolCall(step=8, name="push", effect=EffectClass.IRREVERSIBLE),
    ToolCall(step=9, name="validate", effect=EffectClass.IDEMPOTENT),
]

try:
    assert_forkable(trace, fork_step=7)
except CounterfactualForkError as e:
    # Correct operational outcome: refuse the fork, name the blocker.
    print(f"REFUSED: {e}")
