# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-speculative-branch-rollback-has-become-unsound-in-parallel-drafting-agent-swarms.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-speculative-branch-rollback-has-become-unsound-in-parallel-drafting-agent-swarms.warrant.json
# Markdown SHA-256:   fef670cb1d5da7341a6e79864f710be1678a8257c15f38bc69973ffdc36a0a15
# Code AST SHA-256:   aaca002c062616613ed1e58ac6883e0871605db7f25a9c26044b4bb69bbac3d5
# Verified Classes:   EffectClass, SpeculativeEffectLeak, ToolCall, StagedCall, SpeculationBarrier
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional


class EffectClass(Enum):
    REVERSIBLE = "reversible"
    COMPENSABLE = "compensable"
    IRREVERSIBLE = "irreversible"


class SpeculativeEffectLeak(RuntimeError):
    """Raised when a non-winning speculative branch has released an irreversible
    effect, or when sibling branches converge on an identical irreversible call."""


@dataclass
class ToolCall:
    branch_id: str
    tool: str
    args: dict

    def effect_key(self) -> str:
        blob = f"{self.tool}:{sorted(self.args.items())}".encode()
        return hashlib.sha256(blob).hexdigest()


@dataclass
class StagedCall:
    call: ToolCall
    effect_class: EffectClass
    released: bool = False


@dataclass
class SpeculationBarrier:
    tool_effect_class: Dict[str, EffectClass]
    staged: Dict[str, StagedCall] = field(default_factory=dict)
    committed_branch: Optional[str] = None

    def stage(self, call: ToolCall) -> StagedCall:
        if call.tool not in self.tool_effect_class:
            raise SpeculativeEffectLeak(
                f"tool {call.tool!r} has no declared effect class; "
                "speculative pre-execution is unsound without schema-level classification"
            )
        ec = self.tool_effect_class[call.tool]
        key = call.effect_key()
        if ec is EffectClass.IRREVERSIBLE and key in self.staged:
            prior = self.staged[key]
            if prior.call.branch_id != call.branch_id:
                # Convergence on an irreversible effect is a collision, not a cache hit.
                raise SpeculativeEffectLeak(
                    f"branches {prior.call.branch_id!r} and {call.branch_id!r} "
                    f"converged on irreversible call {call.tool}({call.args}); "
                    "escalate to orchestrator before executing"
                )
        staged = StagedCall(call=call, effect_class=ec)
        self.staged[key] = staged
        return staged

    def release_for_winner(self, branch_id: str) -> List[StagedCall]:
        self.committed_branch = branch_id
        released = []
        for staged in self.staged.values():
            if staged.call.branch_id != branch_id:
                continue
            if staged.effect_class is EffectClass.IRREVERSIBLE:
                staged.released = True
            released.append(staged)
        return released

    def rollback(self, branch_id: str) -> None:
        for staged in self.staged.values():
            if staged.call.branch_id != branch_id:
                continue
            if staged.released:
                raise SpeculativeEffectLeak(
                    f"branch {branch_id!r} was rolled back after releasing "
                    f"irreversible call {staged.call.tool}({staged.call.args}); "
                    "world state now diverges from committed transcript"
                )
            # unreleased staged calls are simply dropped; no effect to compensate.
            self.staged.pop(staged.call.effect_key(), None)
