# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-commit-a-speculative-branch-the-side-effect-compensation-invariant-in-parallel-agent-rollouts.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-commit-a-speculative-branch-the-side-effect-compensation-invariant-in-parallel-agent-rollouts.warrant.json
# Markdown SHA-256:   79cff90e156b9a9dfdb502cddb65e35e25d8c7bfd05e74c19f87cb7e8161fc42
# Code AST SHA-256:   35b7611ef011c03e25f39e2f8b85553f000fddbf44c9cc2eb330b4132f1b33d1
# Verified Classes:   SpeculativeCommitError, EffectKind, Effect, BranchLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class SpeculativeCommitError(RuntimeError):
    """Raised when a speculative branch set cannot be safely committed."""


class EffectKind(Enum):
    COMPENSABLE = "compensable"
    NON_COMPENSABLE = "non_compensable"


@dataclass
class Effect:
    branch_id: str
    idempotency_key: str          # task-derived, NOT branch-derived
    kind: EffectKind
    compensated: bool = False
    compensation_acked: bool = False


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

    def emitted_keys(self) -> set[str]:
        return {e.idempotency_key for e in self.effects}

    def uncompensated(self) -> list[Effect]:
        return [e for e in self.effects if not (e.compensated and e.compensation_acked)]


def assert_committable(
    ledger: BranchLedger,
    winning_branch_id: str,
    assumed_effect_keys: set[str],
) -> None:
    """
    Enforce: E_emitted \\ E_compensated == E_assumed before commit.
    Refuses commit if any losing branch left a non-compensable or
    unacknowledged effect, or if the assumed set diverges from live effects.
    """
    # 1. Idempotency keys must be task-derived, so duplicate intents collapse.
    keys = ledger.emitted_keys()
    if len(keys) != len(ledger.effects):
        # Duplicate idempotency keys mean two branches fired the same intent;
        # the tool layer should have collapsed them, so this is a protocol bug.
        raise SpeculativeCommitError(
            f"duplicate idempotency keys across branches: {keys}"
        )

    # 2. No losing branch may leave a non-compensable effect behind.
    for e in ledger.effects:
        if e.branch_id == winning_branch_id:
            continue
        if e.kind is EffectKind.NON_COMPENSABLE:
            raise SpeculativeCommitError(
                f"branch {e.branch_id} emitted non-compensable effect "
                f"{e.idempotency_key}; commit would orphan it"
            )
        if not (e.compensated and e.compensation_acked):
            raise SpeculativeCommitError(
                f"branch {e.branch_id} effect {e.idempotency_key} "
                f"compensation unacknowledged; cannot commit"
            )

    # 3. The committed plan's assumed effects must equal the live effect set.
    live = {e.idempotency_key for e in ledger.effects if not e.compensated}
    if live != assumed_effect_keys:
        raise SpeculativeCommitError(
            f"effect closure mismatch: live={live} assumed={assumed_effect_keys}"
        )


def commit_branch(ledger: BranchLedger, winner: str, assumed: set[str]) -> str:
    assert_committable(ledger, winner, assumed)
    return "COMMITTED"


if __name__ == "__main__":
    # Two branches attempt the same refund intent (same idempotency key):
    # the tool layer collapses them, so only one effect exists.
    ledger = BranchLedger(effects=[
        Effect("A", "refund:order42:50", EffectKind.COMPENSABLE,
               compensated=True, compensation_acked=True),
        Effect("B", "refund:order42:50", EffectKind.COMPENSABLE),
    ])
    # Duplicate keys -> protocol bug, refuse.
    try:
        commit_branch(ledger, "B", {"refund:order42:50"})
    except SpeculativeCommitError as exc:
        print("refused:", exc)
