# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abandon-a-speculative-branch-write-set-divergence-and-the-rollback-reconciliation-boundary-in-speculative-multi-agent-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abandon-a-speculative-branch-write-set-divergence-and-the-rollback-reconciliation-boundary-in-speculative-multi-agent-execution.warrant.json
# Markdown SHA-256:   32db5c7c78dc929d8b2cafac67b939fbed871bdabe2eee2fcd18a479fc611cc3
# Code AST SHA-256:   cb82803efeabd328b795e007c14c6c775711c35d08578303bc35e54fc2b6597a
# Verified Classes:   SpeculativeRollbackViolation, Effect, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable, Optional


class SpeculativeRollbackViolation(RuntimeError):
    """Raised when a branch is rolled back despite irreversible or observed effects."""


@dataclass
class Effect:
    key: str
    inverse: Optional[Callable[[], None]]
    observed: bool = False


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

    def is_rollback_safe(self) -> bool:
        for effect in self.write_set:
            if effect.inverse is None:
                return False
            if effect.observed:
                return False
        return True


def rollback_branch(branch: Branch, archive: list[Branch]) -> None:
    """
    Roll back a speculative branch only if every effect is reversible and unobserved.
    Otherwise the branch must be promoted to a reconciliation candidate.
    """
    if not branch.is_rollback_safe():
        irreversible = [e.key for e in branch.write_set if e.inverse is None]
        observed = [e.key for e in branch.write_set if e.observed]
        raise SpeculativeRollbackViolation(
            f"branch {branch.branch_id} cannot be rolled back: "
            f"irreversible={irreversible} observed={observed}; "
            f"promote to reconciliation candidate instead"
        )
    # Safe: execute inverses in reverse causal order.
    for effect in reversed(branch.write_set):
        effect.inverse()
    branch.write_set.clear()
    archive.append(branch)


def reconcile(winner: Branch, discarded: list[Branch], archive: list[Branch]) -> Branch:
    """
    Reconcile a winning branch against discarded branches. Discarded branches
    with non-empty or observed write-sets must not be silently dropped.
    """
    for branch in discarded:
        if branch.write_set:
            # Discarded branch left effects; must be compensated or adopted.
            if not branch.is_rollback_safe():
                raise SpeculativeRollbackViolation(
                    f"discarded branch {branch.branch_id} left observable effects "
                    f"that must be reconciled before committing {winner.branch_id}"
                )
            rollback_branch(branch, archive)
        else:
            archive.append(branch)
    return winner
