# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-commit-before-a-speculative-branch-is-reconciled-the-rollback-orphan-invariant-in-cost-aware-multi-agent-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-commit-before-a-speculative-branch-is-reconciled-the-rollback-orphan-invariant-in-cost-aware-multi-agent-execution.warrant.json
# Markdown SHA-256:   99a7e07b22eaa6a8855ac4d4e5bd33cd48e86e73a92f84530f82e721ee56a5f8
# Code AST SHA-256:   e2412cd8dbf7cb4d1c4d4425eb74dc69b0b19f706a02a35a8d9777cc1512926c
# Verified Classes:   RollbackOrphanError, Branch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class RollbackOrphanError(RuntimeError):
    """Raised when a loser branch would be compensated before the winner's
    durability commitment is confirmed, or when selection is revised after
    a durability commitment was made to a now-demoted branch."""
    pass


class Branch:
    def __init__(self, name, effects_externally_visible, reported):
        self.name = name
        self.effects_externally_visible = effects_externally_visible
        self.reported = reported
        self.durable = False
        self.compensated = False


def reconcile(branches, selected, flush, compensate):
    # Step 1: quiesce every branch with externally visible effects,
    # including staggered branches that have not reported.
    for b in branches:
        if b.effects_externally_visible and not b.reported:
            # silence is not inaction; inventory before any rollback
            b.reported = True  # mark as inventoried, not as contributing

    # Step 2: flush the selected branch and CONFIRM durability.
    if not flush(selected):
        # Do NOT compensate losers. Escalate; the ambiguity is recoverable.
        raise RollbackOrphanError(
            f"selected branch {selected.name!r} failed durability confirmation; "
            f"refusing to compensate losers while winner is uncommitted"
        )
    selected.durable = True

    # Step 3: re-score against durable state only.
    rescored = rescore(branches)
    if rescored is not selected and not selected.durable:
        raise RollbackOrphanError(
            f"selection revised to {rescored.name!r} after commitment to "
            f"{selected.name!r}; commitment must be compensated explicitly"
        )

    # Step 4: only now may losers be compensated.
    for b in branches:
        if b is not selected:
            if not selected.durable:
                raise RollbackOrphanError(
                    f"attempted to compensate {b.name!r} before "
                    f"{selected.name!r} was durable"
                )
            compensate(b)
            b.compensated = True
    return selected


def rescore(branches):
    # placeholder: real scorer reads durable state, not in-flight confidence
    return max(branches, key=lambda b: (b.durable, b.reported))
