# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-rollback-reconciliation-has-silently-diverged-in-speculative-parallel-agent-branches.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-rollback-reconciliation-has-silently-diverged-in-speculative-parallel-agent-branches.warrant.json
# Markdown SHA-256:   2cbec2d8b8fd41bf59ffe1e3f9a9f5a5f57c8dd4f276d62a0bbfcc1eb6743899
# Code AST SHA-256:   1fb6e4f3d4880dc12a2a096f746e10a88bc3d6570f31f27d95e7bc128509ea74
# Verified Classes:   RollbackDivergenceError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class RollbackDivergenceError(RuntimeError):
    """Raised when a branch is pruned while holding un-distilled conflict
    evidence or an uncompensated non-compensable side effect."""
    pass


NON_COMPENSABLE = {"mailer.send", "external.mutate", "webhook.emit"}


def prune_branch(branch, reconciliation_ledger):
    """Gate a cost-based prune on evidence drain and compensability.

    Returns True if the branch was safely pruned. Raises if the branch is a
    witness (un-distilled conflicts) or pinned (uncompensated effect)."""
    # 1. Drain conflict observations into the reconciliation record first.
    if branch.conflict_markers:
        reconciliation_ledger.record_conflicts(
            branch_id=branch.id,
            conflicts=branch.conflict_markers,
        )
        if not reconciliation_ledger.conflicts_persisted(branch.id):
            raise RollbackDivergenceError(
                f"branch {branch.id}: conflict drain not persisted; "
                f"pruning would discard witness evidence"
            )

    # 2. Pinned branches cannot be rolled back.
    uncompensated = [
        e for e in branch.side_effects
        if e.tool in NON_COMPENSABLE and not e.compensation_registered
    ]
    if uncompensated:
        raise RollbackDivergenceError(
            f"branch {branch.id}: {len(uncompensated)} uncompensated "
            f"non-compensable effect(s) {[e.id for e in uncompensated]}; "
            f"branch must be pinned, not pruned"
        )

    # 3. Only now is cost a valid pruning signal.
    branch.mark_rolled_back()
    return True


def reconcile(branches, winner_id, ledger):
    """Roll back all non-winners under the drain-before-prune invariant."""
    pinned = []
    for b in branches:
        if b.id == winner_id:
            continue
        try:
            prune_branch(b, ledger)
        except RollbackDivergenceError as exc:
            pinned.append((b.id, str(exc)))
    if pinned:
        # Divergence: the world was touched in ways we cannot retract.
        raise RollbackDivergenceError(
            f"reconciliation incomplete: {len(pinned)} branch(es) pinned; "
            f"winner {winner_id} selection is invalid against pinned effects: {pinned}"
        )
    return ledger.seal()
