# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-merge-a-speculative-branch-after-an-optimistic-tool-call-invalidation-has-been-partially-observed-by-a-do.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-merge-a-speculative-branch-after-an-optimistic-tool-call-invalidation-has-been-partially-observed-by-a-do.warrant.json
# Markdown SHA-256:   7b4394082452fdac49411ea53eb6f8e302ff7e10cc6c56d3d7863b0c9957f7f6
# Code AST SHA-256:   3363992511caa03436b44d5d07a54b96b38814960341776417d22a57a8164fb2
# Verified Classes:   UnsafeSpeculativeMerge, ReadRecord, SpeculativeBranch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UnsafeSpeculativeMerge(RuntimeError):
    """Raised when a rolled-back speculative branch has a non-empty,
    non-reconcilable read-set and therefore cannot be merged as a no-op."""
    pass


@dataclass
class ReadRecord:
    peer_id: str
    speculation_id: str
    derivation_hash_at_read: str
    derivation_hash_now: str
    checkpoint_epoch: int          # peer's checkpoint at time of read
    durable_effect_after_read: bool


@dataclass
class SpeculativeBranch:
    speculation_id: str
    status: str                    # "committed" | "rolled_back" | "quarantined"
    epoch: int
    reads: list[ReadRecord] = field(default_factory=list)
    release_acked: bool = True


def reconcile_branch(branch: SpeculativeBranch) -> str:
    """Return 'merge' or 'quarantine'; raise if merge would be unsound."""
    if branch.status == "committed":
        return "merge"

    if branch.status == "rolled_back":
        if not branch.release_acked:
            # release in flight; a reader may still hold a reservation
            raise UnsafeSpeculativeMerge(
                f"{branch.speculation_id}: release unacked with readers "
                f"{[r.peer_id for r in branch.reads]}"
            )

        for r in branch.reads:
            acted = r.derivation_hash_now != r.derivation_hash_at_read
            if acted and r.durable_effect_after_read:
                # peer consumed the delta and produced durable state
                return "quarantine"
            if acted and r.checkpoint_epoch >= branch.epoch:
                # rollback of reader would be lossy (checkpoint after the read)
                return "quarantine"

        if any(r.derivation_hash_now != r.derivation_hash_at_read
               for r in branch.reads):
            # acted but no durable effect and rollback is non-lossy:
            # require explicit reader rollback before merge
            raise UnsafeSpeculativeMerge(
                f"{branch.speculation_id}: readers acted on delta; "
                "reader rollback required before merge"
            )

        return "merge"   # read-set empty or fully reconciled: genuine no-op

    return "quarantine"
