# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-roll-back-a-speculative-subplan-and-still-commit-its-side-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-roll-back-a-speculative-subplan-and-still-commit-its-side-effects.warrant.json
# Markdown SHA-256:   179f5594fe89ad6ac78751b42eaada0005e3177c3ef807748b90a30dd6045bb2
# Code AST SHA-256:   4f6b9ff99cf1bb183089e8188e75e54d6becb1c2c5d2782ccc4512c89a08e60f
# Verified Classes:   ReconcileInvariantError, Reversibility, Effect, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Hashable


class ReconcileInvariantError(RuntimeError):
    """Raised when a speculative branch cannot be safely discarded."""


class Reversibility(Enum):
    IDEMPOTENT = "idempotent"
    COMPENSABLE = "compensable"
    IRREVERSIBLE = "irreversible"


@dataclass(frozen=True)
class Effect:
    target: Hashable
    prior_value_hash: str
    kind: Reversibility
    compensator: str | None = None


@dataclass
class Branch:
    branch_id: str
    snapshot_id: str
    effects: list[Effect] = field(default_factory=list)


def reconcile(winner: Branch, losers: list[Branch], commit_snapshot: str) -> None:
    # Guard 1: winner's delta must be computed against an ancestor of commit state.
    if winner.snapshot_id != commit_snapshot:
        raise ReconcileInvariantError(
            f"winner {winner.branch_id} delta computed against stale snapshot "
            f"{winner.snapshot_id!r}, commit state is {commit_snapshot!r}"
        )

    winner_keys = {(e.target, e.prior_value_hash) for e in winner.effects}

    # Guard 2: every loser's effect-set must be contained in the winner's,
    # or every uncontained effect must have a registered compensator.
    for loser in losers:
        for eff in loser.effects:
            if (eff.target, eff.prior_value_hash) in winner_keys:
                continue
            if eff.kind is Reversibility.IRREVERSIBLE or eff.compensator is None:
                raise ReconcileInvariantError(
                    f"cannot discard branch {loser.branch_id}: effect on "
                    f"{eff.target!r} (kind={eff.kind.value}) is not contained "
                    f"in winner and has no compensator; escalate to co-winner "
                    f"or deterministic reconciliation"
                )

    # Safe to drop loser branches; effects are contained or compensated.
    for loser in losers:
        loser.effects.clear()
