# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-divergence-during-speculative-multi-agent-execution-with-rollback-and-branch-reconciliation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-divergence-during-speculative-multi-agent-execution-with-rollback-and-branch-reconciliation.warrant.json
# Markdown SHA-256:   2c44635a4a769197c10ea88bee2c9818a883af3da91210f949b830f57fb9c7fb
# Code AST SHA-256:   522879f98d1ab694583285694f2122c5a6de8ce7254cd38bfa4712c6bf56ae0e
# Verified Classes:   RollbackDivergenceError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class RollbackDivergenceError(RuntimeError):
    """Raised when journaled rollback cannot be proven equivalent to non-execution."""
    pass


def reconcile(branches, committed_id, journal):
    # Enforce invariant 1: every journaled write key must be stable.
    for entry in journal:
        if entry.write_key != entry.entry_key:
            raise RollbackDivergenceError(
                f"branch {entry.branch_id} mutated its write key "
                f"({entry.entry_key!r} -> {entry.write_key!r}); "
                f"rollback for this branch is unsound"
            )

    # Enforce invariant 2: reversal must be reverse-total-order per resource.
    by_resource = {}
    for entry in journal:
        by_resource.setdefault(entry.resource, []).append(entry)
    for resource, entries in by_resource.items():
        observed = [e.seq for e in entries]
        if observed != sorted(observed):
            raise RollbackDivergenceError(
                f"resource {resource!r} journal is not in write order; "
                f"reverse-total-order reversal impossible"
            )

    # Enforce invariant 3: no committed branch may have read a speculative write.
    for entry in journal:
        if entry.branch_id != committed_id and entry.read_by == committed_id:
            raise RollbackDivergenceError(
                f"committed branch {committed_id} observed speculative write "
                f"{entry.seq} from branch {entry.branch_id}; "
                f"speculation-window isolation violated"
            )

    # Only now is commit-and-rollback a safe atomic transition.
    return _apply_commit_and_reverse_rollback(branches, committed_id, journal)
