# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-rollback-from-corrupting-shared-agent-state-during-conflict-reconciliation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-rollback-from-corrupting-shared-agent-state-during-conflict-reconciliation.warrant.json
# Markdown SHA-256:   6ac8a1043f7faad5a172af4e08009132d057b6559a60a3ae2b0f2a23877084a7
# Code AST SHA-256:   36c80a3012343275d2c85f71324972614c8385850a318163616ba5525ea148fb
# Verified Classes:   SpeculativeRollbackViolation, EffectLog
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SpeculativeRollbackViolation(RuntimeError):
    """Raised when a speculative branch's effect cannot be safely rolled back
    because it mutated shared state without a captured pre-state."""
    pass


class EffectLog:
    def __init__(self):
        self.entries = []  # (branch_id, effect, base_version, committed)

    def record(self, branch_id, effect, base_version):
        # Write-ahead: log BEFORE the effect lands.
        self.entries.append(
            {"branch": branch_id, "effect": effect,
             "base_version": base_version, "committed": False}
        )

    def commit(self, branch_id, current_version):
        for e in self.entries:
            if e["branch"] == branch_id:
                if e["base_version"] != current_version:
                    raise SpeculativeRollbackViolation(
                        f"branch {branch_id} wrote on stale base "
                        f"{e['base_version']} != {current_version}; "
                        f"effect {e['effect']} cannot be reverted, must merge"
                    )
                e["committed"] = True


def reconcile(winner_id, loser_id, log, current_version):
    # Losers may only be rolled back if every effect was intercepted and
    # either rejected-stale or is a pure scratchpad effect (no shared mutation).
    for e in log.entries:
        if e["branch"] == loser_id and not e["committed"]:
            if e.get("shared_mutation", True):
                raise SpeculativeRollbackViolation(
                    f"cannot roll back branch {loser_id}: effect {e['effect']} "
                    f"reached shared state without a reversible pre-state; "
                    f"escalate to compensating merge"
                )
    log.commit(winner_id, current_version)
    return "reconciled"
