# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-branch-has-silently-contaminated-a-shared-rollback-checkpoint.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-branch-has-silently-contaminated-a-shared-rollback-checkpoint.warrant.json
# Markdown SHA-256:   5a00ded1239f340767bf82ee8c5f5148df8055d6dd50ad8e8454c81044da5030
# Code AST SHA-256:   66bae86df3eb52caa427844d61549d39a972472c05ea2cf3a8b995f90d5f8162
# Verified Classes:   CheckpointPoisoned, Reversibility, Effect, Checkpoint
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum
from typing import Callable, Dict, List, Optional


class CheckpointPoisoned(RuntimeError):
    """Raised when a checkpoint cannot be safely restored because a pruned
    branch left external effects that are not reversible or compensated."""


class Reversibility(Enum):
    REVERSIBLE = "reversible"      # auto-undone on prune
    COMPENSABLE = "compensable"    # inverse action must run synchronously
    IRREVERSIBLE = "irreversible"  # poisons the checkpoint if pruned


@dataclass
class Effect:
    branch_id: str
    tool: str
    target: str
    reversibility: Reversibility
    inverse: Optional[Callable[[], bool]] = None


@dataclass
class Checkpoint:
    cid: str
    substrate_fingerprint: str
    journal: List[Effect] = field(default_factory=list)


def substrate_fingerprint(probe: Callable[[], Dict[str, str]]) -> str:
    live = probe()
    h = hashlib.sha256()
    for k in sorted(live):
        h.update(f"{k}={live[k]};".encode())
    return h.hexdigest()


def prune_and_restore(
    cp: Checkpoint,
    pruned_branch: str,
    probe: Callable[[], Dict[str, str]],
) -> None:
    effects = [e for e in cp.journal if e.branch_id == pruned_branch]

    # Gate 1: irreversible effects poison the checkpoint outright.
    for e in effects:
        if e.reversibility is Reversibility.IRREVERSIBLE:
            raise CheckpointPoisoned(
                f"branch {pruned_branch} committed irreversible effect "
                f"{e.tool}({e.target}); checkpoint {cp.cid} cannot be "
                f"restored cleanly — re-fork from a later checkpoint"
            )

    # Gate 2: compensations must complete synchronously before resume.
    for e in effects:
        if e.reversibility is Reversibility.COMPENSABLE:
            if e.inverse is None or not e.inverse():
                raise CheckpointPoisoned(
                    f"compensation for {e.tool}({e.target}) failed; "
                    f"surviving branches must not resume against {cp.cid}"
                )

    # Gate 3: substrate fingerprint must match the checkpoint's capture.
    live_fp = substrate_fingerprint(probe)
    if live_fp != cp.substrate_fingerprint:
        raise CheckpointPoisoned(
            f"substrate drift at restore of {cp.cid}: expected "
            f"{cp.substrate_fingerprint[:12]}, live {live_fp[:12]} — "
            f"treat as contamination, not nondeterminism"
        )
