# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abandon-a-speculative-branch-after-a-peer-has-already-committed-downstream-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abandon-a-speculative-branch-after-a-peer-has-already-committed-downstream-effects.warrant.json
# Markdown SHA-256:   b4f8646b5d5d5ce507c7075e3328811c842e443759e3bdd4bb8706ab535c27d2
# Code AST SHA-256:   7675886d09c3e8ba3fc927fe43eae9a6025f42ce68d29f75e59da66a7d6aa3eb
# Verified Classes:   SpeculativeCommitmentError, EffectReceipt, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class SpeculativeCommitmentError(RuntimeError):
    """Raised when a branch cannot be rolled back because its effects are already committed."""
    pass


@dataclass
class EffectReceipt:
    effect_id: str
    reversible: bool
    compensate_endpoint: Optional[str]
    token_ttl: float
    emitted_at: float
    write_set: frozenset


@dataclass
class Branch:
    branch_id: str
    effects: list = field(default_factory=list)
    read_snapshot: frozenset = frozenset()


def is_abandonable(branch: Branch, now: float) -> bool:
    """A branch is abandonable only if every effect is reversible with a live token."""
    for e in branch.effects:
        if not e.reversible or e.compensate_endpoint is None:
            return False
        if now - e.emitted_at >= e.token_ttl:
            return False
    return True


def rollback_branch(branch: Branch, now: Optional[float] = None) -> None:
    now = now if now is not None else time.monotonic()
    if not is_abandonable(branch, now):
        # Do NOT silently proceed. Escalate to compensating reconciliation.
        leaked = [e.effect_id for e in branch.effects
                  if not e.reversible or now - e.emitted_at >= e.token_ttl]
        raise SpeculativeCommitmentError(
            f"branch {branch.branch_id} cannot be rolled back; "
            f"committed effects require compensation: {leaked}"
        )
    for e in branch.effects:
        # call e.compensate_endpoint with the branch's rollback token
        pass


def reconcile(branches: list, now: Optional[float] = None) -> str:
    now = now if now is not None else time.monotonic()
    # detect contamination: any branch whose read_snapshot intersects a sibling's write_set
    for b in branches:
        for sib in branches:
            if sib is b:
                continue
            sib_writes = set().union(*(e.write_set for e in sib.effects)) if sib.effects else set()
            if b.read_snapshot & sib_writes:
                raise SpeculativeCommitmentError(
                    f"branch {b.branch_id} observed leaked effects from {sib.branch_id}; "
                    f"reconciliation baseline is contaminated"
                )
    # select consensus, then roll back losers under the commitment barrier
    winner = branches[0]
    for loser in branches[1:]:
        rollback_branch(loser, now=now)
    return winner.branch_id
