# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-reconciles-speculative-parallel-branches-against-a-rollback-journal-that-was-written-by-a-sibling-branch-s-committed-sta.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-reconciles-speculative-parallel-branches-against-a-rollback-journal-that-was-written-by-a-sibling-branch-s-committed-sta.warrant.json
# Markdown SHA-256:   0574ba0151aa535aedec49fbbeae113292b2e07f14dfc2c2fa9390eb4acd21e6
# Code AST SHA-256:   7a478ee9f732d8dd5f704eb571d8c8ed71e3514488d1f8e6b7bb8254085f1921
# Verified Classes:   RollbackPreconditionViolation, JournalEntry, CommitSet
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class RollbackPreconditionViolation(RuntimeError):
    """Raised when a speculative branch's inverse cannot be safely applied
    because the resource no longer matches the state the branch left it in,
    or because the resource is owned by a committed sibling."""


@dataclass
class JournalEntry:
    resource: str
    inverse: Any
    expected_version: int          # version the branch left the resource at
    baseline_version: int          # version at fork time


@dataclass
class CommitSet:
    # resource -> version written by the winning branch
    written: dict[str, int] = field(default_factory=dict)

    def owns_newer(self, resource: str, baseline: int) -> bool:
        return self.written.get(resource, -1) > baseline


def replay_rollback(
    journal: list[JournalEntry],
    current_versions: dict[str, int],
    commits: CommitSet,
) -> list[str]:
    """Apply inverse ops in reverse order, guarded by per-entry preconditions.
    Returns the list of resources actually rolled back. Raises on any
    entry that cannot be safely applied without clobbering a sibling."""
    rolled_back: list[str] = []
    for entry in reversed(journal):
        # Guard 1: winner owns a newer version -> inverse is subsumed.
        if commits.owns_newer(entry.resource, entry.baseline_version):
            raise RollbackPreconditionViolation(
                f"cannot roll back {entry.resource!r}: committed sibling "
                f"wrote version {commits.written[entry.resource]} "
                f"(branch baseline was {entry.baseline_version}); "
                f"inverse would clobber winner"
            )
        # Guard 2: resource drifted from the state this branch left it in.
        live = current_versions.get(entry.resource, -1)
        if live != entry.expected_version:
            raise RollbackPreconditionViolation(
                f"cannot roll back {entry.resource!r}: expected version "
                f"{entry.expected_version}, found {live}; state drifted "
                f"since branch wrote it"
            )
        # Precondition holds: safe to apply the inverse.
        current_versions[entry.resource] = entry.baseline_version
        rolled_back.append(entry.resource)
    return rolled_back


def reconcile(
    winner_journal: list[JournalEntry],
    loser_journals: list[list[JournalEntry]],
    current_versions: dict[str, int],
) -> dict[str, Any]:
    commits = CommitSet()
    for e in winner_journal:
        commits.written[e.resource] = e.expected_version

    report: dict[str, Any] = {"committed": list(commits.written), "rolled_back": [], "escalated": []}
    for idx, journal in enumerate(loser_journals):
        try:
            report["rolled_back"].extend(
                replay_rollback(journal, current_versions, commits)
            )
        except RollbackPreconditionViolation as exc:
            # Do not partially apply: surface to parent for resolution.
            report["escalated"].append({"branch": idx, "reason": str(exc)})
            raise RollbackPreconditionViolation(
                f"branch {idx} requires parent reconciliation: {exc}"
            ) from exc
    return report
