# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-reconciliation-from-corrupting-shared-external-state-when-rollback-is-only-partially-observable.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-reconciliation-from-corrupting-shared-external-state-when-rollback-is-only-partially-observable.warrant.json
# Markdown SHA-256:   092f4ac9190ff6fde3378c59cb408f982c2098e1bf57cfd8ff75c6ae457a0bbc
# Code AST SHA-256:   d2f9253ecdcd878a44435b21df4c5d1060933f7684d5bdf859b000bc47001365
# Verified Classes:   UnconfirmedRollbackError, EffectMonotonicityError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UnconfirmedRollbackError(RuntimeError):
    """Raised when a losing branch's inverse could not be confirmed before commit."""
    pass


class EffectMonotonicityError(RuntimeError):
    """Raised when a surviving branch observed a value from a rolled-back branch."""
    pass


def reconcile(branches, external, winner_id):
    losing = [b for b in branches if b.id != winner_id]

    # Phase 1: confirm every inverse before any commit is published.
    for b in losing:
        if not b.effects_totally_invertible():
            raise UnconfirmedRollbackError(
                f"branch {b.id} has non-invertible effects; must be serialized, not rolled back"
            )
        for effect in b.effects:
            ack = external.apply_inverse(effect)  # must be synchronous
            if not ack.confirmed:
                raise UnconfirmedRollbackError(
                    f"inverse for {effect.key} on branch {b.id} not confirmed: {ack.reason}"
                )

    # Phase 2: re-validate surviving branches against compensated ranges.
    compensated = {e.key for b in losing for e in b.effects}
    for b in branches:
        if b.id == winner_id:
            continue
        overlap = compensated & b.read_keys
        if overlap:
            raise EffectMonotonicityError(
                f"branch {b.id} read compensated keys {sorted(overlap)}; "
                f"demote to losing and re-run"
            )

    # Phase 3: only now is the winner's commit safe to publish.
    return external.publish_commit(winner_id)
