# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-tool-side-effects-when-a-speculative-branch-is-rolled-back-after-a-merge.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-tool-side-effects-when-a-speculative-branch-is-rolled-back-after-a-merge.warrant.json
# Markdown SHA-256:   f5043e5e9cb0c88a83374f30d17ed21a362ed0da2fae00b56079aba6b51aeef7
# Code AST SHA-256:   ec81abf8b1462445ab9e789f3244c6425ad5e7d04fc13291780c169382803303
# Verified Classes:   UncompensableRollbackError, EffectLog
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class UncompensableRollbackError(RuntimeError):
    """Raised when a speculative branch is rolled back but has committed
    non-compensable side effects that the merged state cannot account for."""
    pass


class EffectLog:
    def __init__(self):
        self.committed = []   # (tool, args, compensation or None)
        self.compensated = []

    def record(self, tool: str, args: dict, compensation):
        self.committed.append({"tool": tool, "args": args, "comp": compensation})

    def rollback(self):
        failed = []
        for entry in reversed(self.committed):
            if entry["comp"] is None:
                failed.append(entry)
                continue
            try:
                entry["comp"](entry["args"])
                self.compensated.append(entry)
            except Exception as exc:
                failed.append({**entry, "error": str(exc)})
        if failed:
            raise UncompensableRollbackError(
                f"{len(failed)} effect(s) could not be compensated: "
                f"{[f['tool'] for f in failed]}"
            )


def merge_branches(winner: str, losers: dict[str, EffectLog]) -> str:
    degraded = []
    for branch_id, log in losers.items():
        try:
            log.rollback()
        except UncompensableRollbackError as exc:
            # Do not silently discard; surface divergence to the merged node.
            degraded.append({"branch": branch_id, "reason": str(exc)})
    if degraded:
        return f"merge_status=degraded winner={winner} divergences={degraded}"
    return f"merge_status=clean winner={winner}"
