# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reject-a-speculative-branch-before-rollback-reconciliation-the-commit-order-hazard-in-optimistic-multi-agent-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reject-a-speculative-branch-before-rollback-reconciliation-the-commit-order-hazard-in-optimistic-multi-agent-execution.warrant.json
# Markdown SHA-256:   837ffabe68e6561ba9940cd6502c6b22d16ce5ed9217fa9920cc62c3fc2815e3
# Code AST SHA-256:   45b21baa0ae2be837675639343f58f9d17a37b787a8b36c9d213f3dbf90b33f4
# Verified Classes:   SpeculativeCommitHazard, ReadStamp, Branch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class SpeculativeCommitHazard(RuntimeError):
    """Raised when a speculative branch's commit would encode a rolled-back read."""
    pass


@dataclass
class ReadStamp:
    key: str
    version: int


@dataclass
class Branch:
    branch_id: str
    write_keys: Set[str]
    read_set: Dict[str, int] = field(default_factory=dict)  # key -> version read


def reconcile(
    branches: Dict[str, Branch],
    rolled_back: Dict[str, Set[str]],   # branch_id -> write keys rolled back
    committed_versions: Dict[str, int],  # key -> current committed version
    deterministic: Dict[str, bool],      # branch_id -> re-executable deterministically
) -> Set[str]:
    """Return the set of branch_ids safe to commit; raise on derivation hazard.

    Invariant: a branch may commit only if every read it performed was
    satisfied by a version still committed at reconciliation time. A branch
    that read a rolled-back producer's write must be re-executed, not merged,
    even when its own write keys are disjoint.
    """
    rolled_back_keys: Set[str] = set()
    for keys in rolled_back.values():
        rolled_back_keys |= keys

    safe: Set[str] = set()
    for bid, branch in branches.items():
        for read_key, read_version in branch.read_set.items():
            if read_key in rolled_back_keys:
                # The producer of this read was discarded. The branch's output
                # is a function of state that no longer exists.
                if not deterministic.get(bid, False):
                    raise SpeculativeCommitHazard(
                        f"branch {bid} read {read_key}@{read_version} from a "
                        f"rolled-back producer and is non-deterministic; "
                        f"cannot re-execute safely, refusing commit"
                    )
                # Deterministic: must re-execute from fork, not commit as-is.
                raise SpeculativeCommitHazard(
                    f"branch {bid} read {read_key}@{read_version} from a "
                    f"rolled-back producer; re-execute from fork point "
                    f"before commit (disjoint write keys do not exempt it)"
                )
            current = committed_versions.get(read_key)
            if current is not None and current != read_version:
                raise SpeculativeCommitHazard(
                    f"branch {bid} read {read_key}@{read_version} but "
                    f"committed version is {current}; stale read, re-execute"
                )
        safe.add(bid)
    return safe
