# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-forking-from-corrupting-durable-tool-call-side-effects-on-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-forking-from-corrupting-durable-tool-call-side-effects-on-rollback.warrant.json
# Markdown SHA-256:   bd2d9e2e4e18bae94d41321b8e82719a2384d359e989bbd3548b72abe8b0271a
# Code AST SHA-256:   0614dbc7e092610fe2d857a412fe28c15076c72020ef77e89730f415e42817cf
# Verified Classes:   SpeculativeRollbackViolation, FenceRegistry
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SpeculativeRollbackViolation(RuntimeError):
    """Raised when a rolled-back branch is found to have emitted a durable effect
    that the committed lineage does not own, or when a fenced call lands anyway."""
    pass


class FenceRegistry:
    def __init__(self):
        self._epoch = {}          # idempotency_key -> current fencing epoch
        self._committed = set()   # idempotency_keys owned by winning branches

    def current_epoch(self, key: str) -> int:
        return self._epoch.get(key, 0)

    def bump(self, key: str) -> int:
        self._epoch[key] = self.current_epoch(key) + 1
        return self._epoch[key]

    def admit(self, key: str, token_epoch: int) -> None:
        if token_epoch < self.current_epoch(key):
            raise SpeculativeRollbackViolation(
                f"fenced call landed for key={key!r}: "
                f"token_epoch={token_epoch} < fence_epoch={self.current_epoch(key)}"
            )
        self._committed.add(key)


def rollback_branch(branch, registry: FenceRegistry, touched_keys: list[str]) -> None:
    """Declare a losing branch rolled back. Must fence every key it touched
    and confirm no un-fenced effect escaped before returning."""
    for key in touched_keys:
        registry.bump(key)
    for key in touched_keys:
        if key in registry._committed and key not in branch.owned_keys:
            raise SpeculativeRollbackViolation(
                f"branch {branch.id!r} rolled back but key={key!r} is committed "
                f"under a different owner; orphaned durable effect in lineage"
            )
    # Only now is rollback complete; any later admit() on a bumped key will raise.
