# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-rollback-fidelity-when-speculative-branches-share-a-tool-effect-ledger-across-a-divergent-outcome-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-rollback-fidelity-when-speculative-branches-share-a-tool-effect-ledger-across-a-divergent-outcome-boundary.warrant.json
# Markdown SHA-256:   969fb74f7a1d7365fba616f4c635f9df6556540f1e5a953ad735f3b5c153ea7d
# Code AST SHA-256:   9e72ddc69ab6e17f3ad801193586dcc3a8c756197484b162f16101085ccc6324
# Verified Classes:   RollbackFidelityError, Effect, ResourceChain
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Any


class RollbackFidelityError(RuntimeError):
    """Raised when a speculative rollback cannot be proven to invert exactly the losing branch's effects."""


@dataclass
class Effect:
    branch_tag: str
    resource: str
    op: str
    inverse_op: str
    pre_state_hash: str


@dataclass
class ResourceChain:
    effects: list[Effect] = field(default_factory=list)

    def append(self, effect: Effect) -> None:
        self.effects.append(effect)

    def rollback_to(self, winner_tag: str, committed_winner: str) -> list[Effect]:
        if winner_tag != committed_winner:
            raise RollbackFidelityError(
                f"rollback target {winner_tag!r} disagrees with recorded commit fact "
                f"{committed_winner!r}; refusing to re-derive winner from replay"
            )
        compensations: list[Effect] = []
        for effect in reversed(self.effects):
            if effect.branch_tag == winner_tag:
                continue
            current = self._state_hash()
            if current != effect.pre_state_hash and effect.pre_state_hash:
                raise RollbackFidelityError(
                    f"pre-state hash mismatch on {effect.resource!r} before compensating "
                    f"{effect.op!r} from branch {effect.branch_tag!r}: expected "
                    f"{effect.pre_state_hash[:12]}, observed {current[:12]}"
                )
            compensations.append(effect)
        return compensations

    def _state_hash(self) -> str:
        payload = "|".join(f"{e.branch_tag}:{e.op}" for e in self.effects).encode()
        return hashlib.sha256(payload).hexdigest()


def commit_and_rollback(
    chains: dict[str, ResourceChain],
    winner_tag: str,
    committed_winner: str,
) -> dict[str, list[Effect]]:
    plan: dict[str, list[Effect]] = {}
    for resource, chain in chains.items():
        plan[resource] = chain.rollback_to(winner_tag, committed_winner)
    return plan
