# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-speculative-multi-agent-branches-before-reconciliation-the-rollback-commit-inversion-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-speculative-multi-agent-branches-before-reconciliation-the-rollback-commit-inversion-boundary.warrant.json
# Markdown SHA-256:   42288a345e58fe12f24899679860ccf1b47a0d1f23006cd5ad81652ab9c5c967
# Code AST SHA-256:   ee13bea25f933fbab79b2c9cdfa12aa01cd9566e1a3bc9cc24ffca701b76d80a
# Verified Classes:   RollbackCommitInversionError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class RollbackCommitInversionError(RuntimeError):
    """Raised when a branch is rolled back after a sibling consumed its
    speculative output as committed fact, making rollback undefined."""
    pass


def reconcile(branches, winner_id):
    consumed = {}  # consumer_branch -> set of producer_branch ids
    for b in branches:
        consumed[b.id] = set(b.consumed_speculative_from)

    rolled_back = {b.id for b in branches if b.id != winner_id}

    # Invariant: no retained branch may depend on a rolled-back producer.
    for bid, producers in consumed.items():
        if bid in rolled_back:
            continue
        overlap = producers & rolled_back
        if overlap:
            raise RollbackCommitInversionError(
                f"branch {bid} consumed speculative output from "
                f"rolled-back branch(es) {sorted(overlap)}; "
                f"rollback is undefined, aborting full speculative set"
            )

    for b in branches:
        if b.id == winner_id:
            b.commit()
        else:
            b.rollback()
    return winner_id
