# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-its-causal-trace-before-counterfactual-replay-or-the-replay-silently-rewrites-history.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-its-causal-trace-before-counterfactual-replay-or-the-replay-silently-rewrites-history.warrant.json
# Markdown SHA-256:   435211566f50e1e062df37a931dd75ba43852249868d2b6465b3baa0e2bb5464
# Code AST SHA-256:   cb3651732488a1bb6d27f55885df456c13127e042c84a7ba464a3187fe98cd83
# Verified Classes:   ReplayClassViolation, Trace
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class ReplayClassViolation(RuntimeError):
    """Raised when a counterfactual replay is attempted on a trace that
    cannot satisfy the single-variable isolation invariant."""
    pass


class Trace:
    def __init__(self, trace_id, replay_class, retrieval_snapshot, seed,
                 model_hash, steps):
        self.trace_id = trace_id
        self.replay_class = replay_class          # "A" | "B" | "C"
        self.retrieval_snapshot = retrieval_snapshot  # commit hash or None
        self.seed = seed                          # int or None
        self.model_hash = model_hash              # str or None
        self.steps = steps                        # list of decision points


def replay_counterfactual(trace: Trace, intervention_step: int,
                          substituted_input, current_index_hash: str):
    # Gate 1: class must be replayable.
    if trace.replay_class == "A":
        raise ReplayClassViolation(
            f"trace {trace.trace_id} is Class A (observational); "
            f"counterfactual replay requires Class B or C"
        )

    # Gate 2: sampling determinism must be recorded.
    if trace.seed is None or trace.model_hash is None:
        raise ReplayClassViolation(
            f"trace {trace.trace_id} lacks seed/model_hash; "
            f"replay would be a new trajectory, not a counterfactual"
        )

    # Gate 3: retrieval must be pinned to the original snapshot.
    if trace.retrieval_snapshot is None:
        raise ReplayClassViolation(
            f"trace {trace.trace_id} has no pinned retrieval snapshot; "
            f"re-querying live index {current_index_hash} would "
            f"conflate evidence drift with the intervention"
        )
    if trace.retrieval_snapshot != current_index_hash:
        raise ReplayClassViolation(
            f"retrieval index drifted: trace pinned "
            f"{trace.retrieval_snapshot}, harness offers {current_index_hash}"
        )

    # Gate 4: single-variable isolation at the intervention point.
    step = trace.steps[intervention_step]
    if step.get("cached_sampling"):
        raise ReplayClassViolation(
            f"step {intervention_step} reuses cached sampling; "
            f"substituted input would be ignored (replay theater)"
        )

    # Re-execute with the one substituted input, everything else pinned.
    return _reexecute(trace, intervention_step, substituted_input)


def _reexecute(trace, step, substituted_input):
    # Placeholder: real harness re-runs from pinned snapshot + seed,
    # emitting a node with edge type "counterfactual_of" + intervention attr.
    return {"parent": trace.trace_id, "edge": "counterfactual_of",
            "intervention": {"step": step, "input": substituted_input}}
