# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-speculative-branch-provenance-before-causal-replay-can-be-trusted.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-speculative-branch-provenance-before-causal-replay-can-be-trusted.warrant.json
# Markdown SHA-256:   9ca78f74cee08dc4dee976df92be76cc208eb199e1405e60a964b5c00ba7f4e3
# Code AST SHA-256:   aff7587857869b9e57c51f8dacd2fad95270f05026cb73bc09b74df74698dcb6
# Verified Classes:   UnrecordedReadSetFault, Mutation, ReadEvent
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class UnrecordedReadSetFault(RuntimeError):
    """Raised when a speculative branch reads shared mutable state without
    recording the branch-local read-set, making deterministic replay unsound."""
    pass


@dataclass(frozen=True)
class Mutation:
    branch_id: str
    seq: int


@dataclass
class ReadEvent:
    branch_id: str
    fork_event_id: str
    key: str
    shared_scoped: bool
    read_set: Set[Mutation] = field(default_factory=set)


def seal_trace(reads: list[ReadEvent]) -> None:
    """Construction-time guardrail: a trace may not be sealed if any
    shared-scoped read lacks a recorded read-set."""
    for r in reads:
        if r.shared_scoped and not r.read_set:
            raise UnrecordedReadSetFault(
                f"branch {r.branch_id} read shared key {r.key!r} under fork "
                f"{r.fork_event_id} with empty read-set; replay would "
                f"reconstruct a different causal history"
            )


def replay_branch_state(
    branch_id: str,
    reads: list[ReadEvent],
    store: Dict[str, list[Tuple[Mutation, str]]],
) -> Dict[str, str]:
    """Reconstruct branch-local view of shared keys using recorded read-sets."""
    seal_trace(reads)
    view: Dict[str, str] = {}
    for r in reads:
        if r.branch_id != branch_id:
            continue
        if not r.shared_scoped:
            continue
        visible = [
            (m, v) for (m, v) in store.get(r.key, [])
            if m in r.read_set
        ]
        if not visible:
            raise UnrecordedReadSetFault(
                f"read-set for {r.key!r} in branch {branch_id} references "
                f"mutations absent from store; trace is corrupt or partial"
            )
        visible.sort(key=lambda mv: mv[0].seq)
        view[r.key] = visible[-1][1]
    return view
