# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abort-a-replayed-branch-to-preserve-audit-integrity-under-speculative-multi-agent-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abort-a-replayed-branch-to-preserve-audit-integrity-under-speculative-multi-agent-execution.warrant.json
# Markdown SHA-256:   a4a854afb9334071ebdab8c3ead40e7037295035c6e51dbf89740ec9c7b4f5a9
# Code AST SHA-256:   235bb3cdd56629c5573d516bf72cc80b94bd6cca4f730c5e3c8263f1fb2e3143
# Verified Classes:   BranchReconciliationAbort, Provenance, ReadEvent
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class BranchReconciliationAbort(RuntimeError):
    """Raised when a speculative branch cannot be reconciled into the committed
    trace without violating replay admissibility. Aborting is mandatory: an
    equivalent terminal state is not evidence of a valid witness."""
    pass


@dataclass(frozen=True)
class Provenance:
    slot: str
    writer_branch_id: str
    value_hash: str
    wall_clock: float


@dataclass(frozen=True)
class ReadEvent:
    slot: str
    consumer_branch_id: str
    consumed_provenance: Optional[Provenance]


def reconcile_branch(
    committed_reads: list[ReadEvent],
    committed_writes: dict[str, Provenance],
    discarded_writes: dict[str, Provenance],
    non_idempotent_calls_on_replay_path: list[str],
    recorded_seed: Optional[int],
    model_hash_original: str,
    model_hash_replay: str,
) -> None:
    if recorded_seed is None:
        raise BranchReconciliationAbort(
            "no sampling seed recorded; replay is not a witness for the original decision"
        )
    if model_hash_original != model_hash_replay:
        raise BranchReconciliationAbort(
            f"model version drift: original={model_hash_original} replay={model_hash_replay}; "
            "re-execution is a new decision, not a replay"
        )
    if non_idempotent_calls_on_replay_path:
        raise BranchReconciliationAbort(
            "non-idempotent tool calls on replay path would re-apply side effects: "
            f"{non_idempotent_calls_on_replay_path}"
        )

    for read in committed_reads:
        slot = read.slot
        if slot in committed_writes:
            continue
        prov = discarded_writes.get(slot)
        if prov is None:
            raise BranchReconciliationAbort(
                f"unbound read of slot {slot!r} by branch {read.consumer_branch_id!r}: "
                "no committed writer and no discarded-branch provenance"
            )
        if read.consumed_provenance is None:
            raise BranchReconciliationAbort(
                f"read of {slot!r} by {read.consumer_branch_id!r} lacks consumed-provenance tuple; "
                f"discarded writer {prov.writer_branch_id!r} cannot be injected"
            )
        if read.consumed_provenance.value_hash != prov.value_hash:
            raise BranchReconciliationAbort(
                f"provenance mismatch on {slot!r}: committed read consumed "
                f"{read.consumed_provenance.value_hash}, discarded branch wrote {prov.value_hash}"
            )
    # All reads bound; reconciliation may proceed with virtual-write injection.
