# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-rollback-fan-out-when-speculative-agent-branches-share-a-mutable-external-side-effect-log.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-rollback-fan-out-when-speculative-agent-branches-share-a-mutable-external-side-effect-log.warrant.json
# Markdown SHA-256:   b0ebe8d073d405332f4c8adbd2335c3779b4a0c4338174e6f784465ef292df21
# Code AST SHA-256:   3d2682bd9f9b144a9b6173ddb23adb8b4b64801e700b60a4bd26c4757c06e694
# Verified Classes:   SpeculativeCommitViolation, Effect, EffectChannel
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class SpeculativeCommitViolation(RuntimeError):
    """Raised when a speculative branch effect cannot be reconciled to a single winner."""


@dataclass
class Effect:
    branch_id: str
    effect_id: str
    amount: int
    settled: bool = False
    voided: bool = False


@dataclass
class EffectChannel:
    # The channel of record. The orchestrator must reconcile against THIS,
    # not against any local ledger it maintains in parallel.
    effects: Dict[str, Effect] = field(default_factory=dict)

    def commit(self, effect: Effect) -> None:
        if effect.effect_id in self.effects:
            raise SpeculativeCommitViolation(
                f"duplicate effect_id {effect.effect_id!r} committed by {effect.branch_id!r}"
            )
        self.effects[effect.effect_id] = effect

    def settle(self, effect_id: str) -> None:
        self.effects[effect_id].settled = True

    def void(self, effect_id: str) -> None:
        e = self.effects[effect_id]
        if e.settled:
            # A void against a settled effect is a credit note, not a reversal.
            # It must not be counted as a successful rollback.
            raise SpeculativeCommitViolation(
                f"cannot void settled effect {effect_id!r}; "
                f"reconciliation requires pre-settlement rollback"
            )
        e.voided = True


def reconcile(
    channel: EffectChannel,
    winner_branch: str,
    branch_ids: List[str],
) -> List[str]:
    """Resolve speculative effects to a single winner.

    Returns the list of effect_ids that remain externally visible.
    Raises if any losing branch has an effect that cannot be cleanly rolled back.
    """
    residual: List[str] = []
    for eid, e in channel.effects.items():
        if e.branch_id == winner_branch:
            residual.append(eid)
            continue
        if e.branch_id not in branch_ids:
            raise SpeculativeCommitViolation(
                f"effect {eid!r} has unknown branch token {e.branch_id!r}; "
                f"cannot attribute to a speculative branch"
            )
        if e.settled:
            raise SpeculativeCommitViolation(
                f"losing branch {e.branch_id!r} effect {eid!r} already settled; "
                f"rollback window closed before reconciliation"
            )
        channel.void(eid)
    if len(residual) != 1:
        # The invariant: exactly one visible effect per reconciliation unit.
        raise SpeculativeCommitViolation(
            f"expected exactly one winning effect, found {len(residual)}: {residual}"
        )
    return residual
