# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-speculative-branch-contamination-when-optimistic-tool-call-prefetching-commits-side-effects-before-the-verifier-rejects-th.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-speculative-branch-contamination-when-optimistic-tool-call-prefetching-commits-side-effects-before-the-verifier-rejects-th.warrant.json
# Markdown SHA-256:   54b84f3ecf7725b68440b771f7c80f22a3a1d175a7971002985a3c3fa2e01b46
# Code AST SHA-256:   d95b4656b422a28823cabc2dc5fc6e8e7a4e52669b9d027cc145e83d75e967fc
# Verified Classes:   ReversibilityClass, SpeculativeContamination, StagedEffect, EffectLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, Set


class ReversibilityClass(Enum):
    READ = "read"
    STAGEABLE_WRITE = "stageable_write"
    UNSTAGEABLE_WRITE = "unstageable_write"


class SpeculativeContamination(RuntimeError):
    """Raised when a branch's committed effects do not reconcile with staged effects."""
    pass


@dataclass
class StagedEffect:
    branch_id: str
    tool: str
    payload: dict
    commit_token: str = "pending"  # pending | committed | aborted


@dataclass
class EffectLedger:
    staged: Dict[str, StagedEffect] = field(default_factory=dict)

    def stage(self, effect: StagedEffect) -> None:
        key = f"{effect.branch_id}:{effect.tool}:{hash(frozenset(effect.payload.items()))}"
        self.staged[key] = effect

    def abort_branch(self, branch_id: str) -> None:
        # Drain staged effects; also catches late arrivals if called again after dispatch.
        for key, eff in list(self.staged.items()):
            if eff.branch_id == branch_id and eff.commit_token == "pending":
                eff.commit_token = "aborted"

    def reconcile_commit(self, branch_id: str, intended: Set[str]) -> None:
        staged_for_branch = {
            k for k, e in self.staged.items()
            if e.branch_id == branch_id and e.commit_token == "pending"
        }
        orphaned = staged_for_branch - intended
        if orphaned:
            raise SpeculativeContamination(
                f"Branch {branch_id} has {len(orphaned)} orphaned staged effect(s) "
                f"not present in intended commit set: {orphaned}"
            )
        for k in intended:
            if k not in self.staged:
                raise SpeculativeContamination(
                    f"Branch {branch_id} intends to commit effect {k} that was never staged"
                )
            self.staged[k].commit_token = "committed"


def prefetch_or_dispatch(
    ledger: EffectLedger,
    branch_id: str,
    tool: str,
    payload: dict,
    reversibility: ReversibilityClass,
) -> str:
    if reversibility is ReversibilityClass.UNSTAGEABLE_WRITE:
        # Fail closed: no speculative dispatch of unstageable mutations.
        return "sequential"
    if reversibility is ReversibilityClass.READ:
        return "prefetch_read"
    effect = StagedEffect(branch_id=branch_id, tool=tool, payload=payload)
    ledger.stage(effect)
    return "prefetch_staged"


def commit_verified_branch(ledger: EffectLedger, branch_id: str, intended_keys: Set[str]) -> None:
    # Must be called only after verifier accepts the branch.
    ledger.reconcile_commit(branch_id, intended_keys)


def rollback_rejected_branch(ledger: EffectLedger, branch_id: str) -> None:
    ledger.abort_branch(branch_id)
    # Caller must also re-invoke abort_branch on prefetch-ack late arrival,
    # otherwise the early-rollback race orphans the effect.
