# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-agent-rollback-from-committing-phantom-side-effects-during-compensation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-agent-rollback-from-committing-phantom-side-effects-during-compensation.warrant.json
# Markdown SHA-256:   cbed252244f228bf17edede47e825e5976e5a11c1e0fbb05b761887ad13ca0b0
# Code AST SHA-256:   5dc8affb56b2c60e087026fe93ca10ea7a622eb9e5b00cb9e436bb1f1fd42fc5
# Verified Classes:   PhantomCompensationError, SnapshotDriftError, ReservationRecord, Branch, SpeculativeOrchestrator
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Dict, List


class PhantomCompensationError(RuntimeError):
    """Raised when a compensation would act on a handle shared with a live branch."""
    pass


class SnapshotDriftError(RuntimeError):
    """Raised when a commit value is derived from a read taken after compensation began."""
    pass


@dataclass
class ReservationRecord:
    reservation_id: str
    item: str
    qty: int
    branch: str
    effect_handle: str  # backend key; shared handles => non-isolated
    recorded_at: float = field(default_factory=time.time)


@dataclass
class Branch:
    name: str
    records: List[ReservationRecord] = field(default_factory=list)


class SpeculativeOrchestrator:
    def __init__(self):
        self.branches: Dict[str, Branch] = {}
        self.compensation_started_at: float = float("inf")

    def register(self, rec: ReservationRecord) -> None:
        self.branches.setdefault(rec.branch, Branch(rec.branch)).records.append(rec)

    def _assert_isolated(self, target: Branch, survivors: List[Branch]) -> None:
        target_handles = {r.effect_handle for r in target.records}
        for sib in survivors:
            shared = target_handles & {r.effect_handle for r in sib.records}
            if shared:
                raise PhantomCompensationError(
                    f"branch {target.name!r} shares effect handles {shared} "
                    f"with live survivor {sib.name!r}; compensation would "
                    f"mutate survivor state"
                )

    def compensate(self, target: Branch, survivors: List[Branch]) -> None:
        self._assert_isolated(target, survivors)
        self.compensation_started_at = min(
            self.compensation_started_at, time.time()
        )
        for rec in target.records:
            # backend release() elided; in real code this is a tool call
            pass

    def commit(self, survivor: Branch, observed_qty: int) -> int:
        pinned = sum(r.qty for r in survivor.records)
        if observed_qty != pinned:
            raise SnapshotDriftError(
                f"survivor {survivor.name!r}: observed qty {observed_qty} "
                f"differs from pinned {pinned}; read taken after "
                f"compensation at t={self.compensation_started_at} is unsafe"
            )
        return pinned


def run_speculative_round(orch: SpeculativeOrchestrator) -> int:
    a = Branch("A")
    b = Branch("B")
    c = Branch("C")
    # shared backend handle "item=X" across branches => non-isolated
    orch.register(ReservationRecord("r-a", "X", 5, "A", "item=X"))
    orch.register(ReservationRecord("r-b", "X", 5, "B", "item=X"))
    orch.register(ReservationRecord("r-c", "X", 5, "C", "item=X"))

    # Attempt to compensate siblings of survivor B.
    for dead in (a, c):
        orch.compensate(dead, survivors=[b])  # raises on first dead branch

    # If isolation held, commit from a pinned value only.
    return orch.commit(b, observed_qty=10)
