# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-when-parallel-speculative-branches-have-silently-diverged-past-reconciliation-the-write-epoch-skew-failure-in-forked.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-when-parallel-speculative-branches-have-silently-diverged-past-reconciliation-the-write-epoch-skew-failure-in-forked.warrant.json
# Markdown SHA-256:   60858b3f5a6ed23868f95dbf0ecf15e341380565136174f19abefd4e77661b08
# Code AST SHA-256:   395588141bbbef92ef4bfb24eb76cbc29f384353e5c171455c443314d26e5e06
# Verified Classes:   WriteEpochSkewError, PreStateDriftError, Branch, Reconciler
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set


class WriteEpochSkewError(RuntimeError):
    """Raised when a winning speculative branch's write set does not dominate
    the union of all branches' write sets on shared resources."""
    pass


class PreStateDriftError(RuntimeError):
    """Raised when the world changed between fork and reconciliation for
    reasons not attributable to any branch in the fork set."""
    pass


@dataclass
class Branch:
    branch_id: str
    writes: Dict[str, int] = field(default_factory=dict)  # resource_id -> epoch


@dataclass
class Reconciler:
    pre_state_hash: str
    tracked_resources: Set[str]
    branches: Dict[str, Branch] = field(default_factory=dict)

    def record_write(self, branch_id: str, resource_id: str, epoch: int) -> None:
        if resource_id not in self.tracked_resources:
            # Untracked write: the dominance check cannot see it. Refuse to
            # pretend the fork is safe.
            raise WriteEpochSkewError(
                f"branch {branch_id} wrote untracked resource {resource_id!r}; "
                "resource registry is not closed under permitted tools"
            )
        self.branches.setdefault(branch_id, Branch(branch_id)).writes[resource_id] = epoch

    def reconcile(self, winner_id: str, observed_state_hash: str) -> str:
        if observed_state_hash != self.pre_state_hash:
            # Drift not attributable to a branch write is contamination.
            raise PreStateDriftError(
                f"pre-state hash {self.pre_state_hash} != observed {observed_state_hash} "
                "at reconciliation; fork snapshot aged"
            )
        winner = self.branches[winner_id]
        union: Dict[str, int] = {}
        for b in self.branches.values():
            for res, epoch in b.writes.items():
                union[res] = max(union.get(res, -1), epoch)
        missing = {res for res in union if res not in winner.writes}
        if missing:
            raise WriteEpochSkewError(
                f"winner {winner_id} does not dominate write set; "
                f"losing-branch writes already committed to {sorted(missing)}"
            )
        return winner_id
