# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abandon-speculative-branches-rollback-invalidation-under-shared-tool-side-effects-in-multi-agent-speculative-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abandon-speculative-branches-rollback-invalidation-under-shared-tool-side-effects-in-multi-agent-speculative-execution.warrant.json
# Markdown SHA-256:   596a71fa740181b16ea2dfdb75aacc0b082134a94ab6a6c07b43338112f48e7c
# Code AST SHA-256:   b4995e03faab367d0cc18cd5500b71ec62299f42098908b7e4939adaca6a29c7
# Verified Classes:   SpeculationRollbackError, EffectClass, Effect, Branch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Iterable


class SpeculationRollbackError(RuntimeError):
    """Raised when a speculative round cannot be safely committed or rolled back."""


class EffectClass(Enum):
    READ_ONLY = "read_only"
    OVERLAY = "overlay"      # branch-scoped, safely discardable
    SHARED_WRITE = "shared_write"  # escapes the branch envelope


@dataclass(frozen=True)
class Effect:
    branch_id: str
    tool: str
    effect_class: EffectClass
    resource: str
    epoch: int


@dataclass
class Branch:
    branch_id: str
    effects: list[Effect] = field(default_factory=list)
    score: float = 0.0
    session_warrant_owner: str | None = None  # branch that negotiated the pooled session


def _read_write_intersection(winner: Branch, losers: Iterable[Branch]) -> set[str]:
    winner_reads = {e.resource for e in winner.effects if e.effect_class is EffectClass.READ_ONLY}
    contaminated: set[str] = set()
    for loser in losers:
        for e in loser.effects:
            if e.effect_class is EffectClass.SHARED_WRITE and e.resource in winner_reads:
                contaminated.add(e.resource)
    return contaminated


def select_and_commit(branches: list[Branch], snapshot_epoch: int) -> Branch:
    if not branches:
        raise SpeculationRollbackError("no branches to select from")

    winner = max(branches, key=lambda b: b.score)
    losers = [b for b in branches if b is not winner]

    # Guard 1: uncontained writes by any branch invalidate the round.
    for b in branches:
        for e in b.effects:
            if e.effect_class is EffectClass.SHARED_WRITE and e.epoch < snapshot_epoch:
                raise SpeculationRollbackError(
                    f"branch {b.branch_id} committed shared write to {e.resource} "
                    f"before divergence resolved (epoch {e.epoch} < snapshot {snapshot_epoch})"
                )

    # Guard 2: winner's read-set must not intersect a loser's write-set.
    contaminated = _read_write_intersection(winner, losers)
    if contaminated:
        raise SpeculationRollbackError(
            f"winner {winner.branch_id} read resources mutated by discarded siblings: "
            f"{sorted(contaminated)}; abort round and replay from snapshot"
        )

    # Guard 3: pooled session warrant must not be inherited from a discarded branch.
    if winner.session_warrant_owner is not None and winner.session_warrant_owner != winner.branch_id:
        raise SpeculationRollbackError(
            f"winner {winner.branch_id} inherited session warrant negotiated by discarded "
            f"branch {winner.session_warrant_owner}; renegotiate before commit"
        )

    return winner
