# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-divergence-when-speculative-agent-branches-are-rolled-back-and-merged.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-divergence-when-speculative-agent-branches-are-rolled-back-and-merged.warrant.json
# Markdown SHA-256:   23bc276bdfa84146fdc49fcd97081174f7d5ca738fec261ffbe9affa5467636d
# Code AST SHA-256:   14f13d121409446574ac30c7d96f0309896f6ed2b68c15193fc05ac2dda27682
# Verified Classes:   SpeculativeMergeError, BranchJournal
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class SpeculativeMergeError(RuntimeError):
    """Raised when a speculative fork cannot be safely merged or rolled back."""


@dataclass(frozen=True)
class BranchJournal:
    branch_id: str
    read_set: FrozenSet[str]          # resource ids + version stamps read
    write_set: FrozenSet[str]         # resource ids written
    invertible: bool                  # can effects be honestly undone?
    declared_post_state: dict
    passed_verification: bool


def reconcile_speculative_fork(
    journals: list[BranchJournal],
    committed_state: dict,
) -> str:
    """Select a winner only if read-write isolation and invertibility hold.

    Returns the winning branch id. Raises SpeculativeMergeError when the
    fork must be discarded and re-executed serially.
    """
    if not journals:
        raise SpeculativeMergeError("empty fork: nothing to reconcile")

    passing = [j for j in journals if j.passed_verification]

    # Invariant 1: any losing branch with non-invertible effects poisons the fork.
    for j in journals:
        if not j.passed_verification and not j.invertible and j.write_set:
            raise SpeculativeMergeError(
                f"branch {j.branch_id} has non-invertible effects "
                f"{sorted(j.write_set)}; rollback would be a lie, "
                f"escalate to serialized re-execution"
            )

    # Invariant 2: a passing branch whose reads intersect any sibling's writes
    # is CONTAMINATED and ineligible to win.
    eligible = []
    for w in passing:
        contaminated_by = [
            s.branch_id for s in journals
            if s.branch_id != w.branch_id and (w.read_set & s.write_set)
        ]
        if contaminated_by:
            raise SpeculativeMergeError(
                f"branch {w.branch_id} read state written by siblings "
                f"{contaminated_by}; verification is contaminated, "
                f"discard fork"
            )
        eligible.append(w)

    # Invariant 3: mutually exclusive passing world-models are a hard stop.
    if len(eligible) > 1:
        models = {frozenset(w.declared_post_state.items()) for w in eligible}
        if len(models) > 1:
            raise SpeculativeMergeError(
                f"passing branches {[w.branch_id for w in eligible]} "
                f"declare mutually exclusive post-states; "
                f"at least one verifier read a contaminated snapshot"
            )

    if not eligible:
        raise SpeculativeMergeError("no uncontaminated passing branch; discard fork")

    winner = max(eligible, key=lambda j: len(j.declared_post_state))
    return winner.branch_id
