# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-commits-a-branch-that-outlives-its-rollback-horizon.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-commits-a-branch-that-outlives-its-rollback-horizon.warrant.json
# Markdown SHA-256:   0b2538997fb8041cab11e3677248cccd011c62c5579cdcd6993d4e4022c77cb6
# Code AST SHA-256:   f9ba80328aaff83305e7f2c60bca41bec5f6099b6509fed32e3a314f2d2049c8
# Verified Classes:   RollbackHorizonViolation, Effect, CausalLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set, List


class RollbackHorizonViolation(RuntimeError):
    """Raised when a branch effect escapes the executor's rollback horizon."""
    pass


@dataclass
class Effect:
    causal_key: str          # branch_epoch + effect_seq
    branch_id: str
    payload: dict
    observers: Set[str] = field(default_factory=set)


class CausalLedger:
    def __init__(self) -> None:
        self._effects: Dict[str, Effect] = {}
        self._tombstones: Set[str] = set()
        self._observer_index: Dict[str, Set[str]] = {}  # observer -> causal_keys

    def register(self, effect: Effect) -> None:
        if not effect.observers:
            # Emit-and-forget: branch is trying to leak past the horizon.
            raise RollbackHorizonViolation(
                f"effect {effect.causal_key} from branch {effect.branch_id} "
                f"has no resolvable observer set; cannot be rolled back soundly"
            )
        self._effects[effect.causal_key] = effect
        for obs in effect.observers:
            self._observer_index.setdefault(obs, set()).add(effect.causal_key)

    def rollback(self, branch_id: str, reachable: Set[str]) -> List[str]:
        """Emit tombstones for all effects of a branch. Returns compensation targets."""
        targets: List[str] = []
        for key, eff in self._effects.items():
            if eff.branch_id != branch_id or key in self._tombstones:
                continue
            # Invariant: every observer of the effect must be reachable.
            missing = eff.observers - reachable
            if missing:
                raise RollbackHorizonViolation(
                    f"rollback of {branch_id} cannot reach observers {missing} "
                    f"for effect {key}; causal leak would orphan derived state"
                )
            self._tombstones.add(key)
            targets.extend(eff.observers)
        return targets

    def is_rolled_back(self, causal_key: str) -> bool:
        return causal_key in self._tombstones


def admit_speculative_effect(ledger: CausalLedger, effect: Effect) -> None:
    """Tool-layer admission gate: called before any externally observable emit."""
    if effect.branch_id.startswith("speculative:") and not effect.observers:
        raise RollbackHorizonViolation(
            f"speculative branch {effect.branch_id} attempted emit of "
            f"{effect.causal_key} without observer enumeration; "
            f"either defer until commit or register observers in the causal ledger"
        )
    ledger.register(effect)


def reconcile(ledger: CausalLedger, winner: str, losers: List[str],
              reachable: Set[str]) -> None:
    for loser in losers:
        try:
            ledger.rollback(loser, reachable)
        except RollbackHorizonViolation as exc:
            # Do not silently proceed: escalate to the reconciler's supervisor.
            raise RollbackHorizonViolation(
                f"cannot reconcile: loser {loser} has effects outside the "
                f"rollback horizon ({exc}); winner {winner} may depend on "
                f"phantom preconditions"
            ) from exc
