# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-speculative-branch-divergence-has-become-unreconcilable-under-tool-side-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-speculative-branch-divergence-has-become-unreconcilable-under-tool-side-effects.warrant.json
# Markdown SHA-256:   170c49510d0d529e4912fcab9831614f13daba0ff1837efc89ff6b8a568bda90
# Code AST SHA-256:   151cb2ca369c5f08a77ae44656ec87743757e8281d06f38f6a4f2c300b34c450
# Verified Classes:   UnreconcilableSpeculationError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UnreconcilableSpeculationError(RuntimeError):
    """Raised when speculative branches have committed overlapping or undeclared
    effects such that rollback-and-select can no longer produce a sound state."""
    pass


def reconcile_branches(branches, ledger):
    declared = set()
    resource_ops = {}
    for b in branches:
        declared |= set(b.declared_effects)
        for eff in b.committed_effects:
            key = (eff.resource, eff.operation_class)
            resource_ops.setdefault(key, []).append((b.id, eff))

    # Signal 1: orphaned effects exist in the ledger but no branch declares them.
    orphans = set(ledger.effects) - declared
    if orphans:
        raise UnreconcilableSpeculationError(
            f"orphaned effects with no owning branch: {sorted(map(str, orphans))}"
        )

    # Signal 3: overlapping effects on a shared resource across live branches.
    for key, owners in resource_ops.items():
        live = {bid for bid, _ in owners if not _is_reversible(owners, bid)}
        if len({bid for bid, _ in owners}) > 1 and live:
            raise UnreconcilableSpeculationError(
                f"overlapping irreversible effects on {key}: "
                f"branches {sorted(bid for bid, _ in owners)}"
            )

    # Signal 2: stale rollback tokens (watermark precedes committed effect).
    for b in branches:
        if b.rollback_token.watermark < ledger.position_of(b.committed_effects):
            raise UnreconcilableSpeculationError(
                f"branch {b.id} rollback token is stale; reversal would be partial"
            )

    winner = max(branches, key=lambda b: b.confidence)
    for b in branches:
        if b.id != winner.id:
            ledger.rollback(b.rollback_token)
    return winner


def _is_reversible(owners, bid):
    return all(eff.reversible for _, eff in owners if _ == bid)
