# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-irreconcilable-speculative-branches-before-committing-a-multi-agent-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-irreconcilable-speculative-branches-before-committing-a-multi-agent-rollback.warrant.json
# Markdown SHA-256:   5e403e8965d96201fb348792cec824ac7f8d62e1b515832499151bb5c923215b
# Code AST SHA-256:   ebac32b70ae4403b9256bc8edaa2af68087d41b60cbcb0b0ee4ee7ca101ca9bd
# Verified Classes:   IrreconcilableSpeculationError, ValidationRecord
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class IrreconcilableSpeculationError(RuntimeError):
    """Raised when speculative branches validated contradictory post-states
    against the same snapshot for the same resource, before commit."""
    pass


@dataclass(frozen=True)
class ValidationRecord:
    branch_id: str
    resource: str
    snapshot_token: str
    post_state: str  # canonical, comparable representation


def assert_reconcilable(records: Iterable[ValidationRecord]) -> None:
    """Fail closed if any two branches produced distinct post-states for the
    same (resource, snapshot_token). Must run before side-effect dispatch."""
    seen: dict[tuple[str, str], tuple[str, str]] = {}
    for rec in records:
        key = (rec.resource, rec.snapshot_token)
        if key in seen:
            prior_branch, prior_state = seen[key]
            if prior_state != rec.post_state:
                raise IrreconcilableSpeculationError(
                    f"resource={rec.resource!r} snapshot={rec.snapshot_token!r}: "
                    f"branch {prior_branch!r} produced {prior_state!r} but "
                    f"branch {rec.branch_id!r} produced {rec.post_state!r}; "
                    f"both valid against the same pre-speculation snapshot. "
                    f"Refusing to commit; no winner may be selected."
                )
        else:
            seen[key] = (rec.branch_id, rec.post_state)
