# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-invalidate-speculative-branch-results-when-a-hedged-parallel-tool-call-commits-a-side-effect-before-rollback-quiesc.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-invalidate-speculative-branch-results-when-a-hedged-parallel-tool-call-commits-a-side-effect-before-rollback-quiesc.warrant.json
# Markdown SHA-256:   009b286c8069128c73ffed39bd15d61eee72d9c688d3a619c33773bc31bf4a33
# Code AST SHA-256:   35b3fefbe8f5c8b4a81fe32c4563dda8f1bc896f21ac3a6ce0abc3f48ad22b88
# Verified Classes:   BranchContaminationError, EffectRecord, ForkGroup
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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

class BranchContaminationError(RuntimeError):
    """Raised when a surviving branch's effects depend on a discarded branch's speculative write."""
    pass

@dataclass
class EffectRecord:
    fork_group_id: str
    branch_id: str
    effect_class: str          # "read_only" | "idempotent" | "non_idempotent"
    target_resource: str
    pre_state_hash: str
    post_state_hash: Optional[str] = None
    has_compensating_inverse: bool = False

@dataclass
class ForkGroup:
    group_id: str
    ledger: List[EffectRecord] = field(default_factory=list)
    winner: Optional[str] = None
    discarded: List[str] = field(default_factory=list)

def arbitrate(group: ForkGroup, winner: str, discarded: List[str]) -> None:
    group.winner = winner
    group.discarded = discarded

    # Non-idempotent effects with no inverse on a discarded branch: cannot roll back.
    for rec in group.ledger:
        if rec.branch_id in discarded and rec.effect_class == "non_idempotent":
            if not rec.has_compensating_inverse:
                raise BranchContaminationError(
                    f"fork group {group.group_id}: discarded branch {rec.branch_id} "
                    f"committed non-invertible effect on {rec.target_resource}; "
                    f"fork group must abort to last clean checkpoint, not select {winner}"
                )

    # Survivor reads whose pre-state was mutated by a discarded branch are contaminated.
    discarded_writes: Dict[str, str] = {
        rec.target_resource: rec.post_state_hash
        for rec in group.ledger
        if rec.branch_id in discarded and rec.post_state_hash is not None
    }
    for rec in group.ledger:
        if rec.branch_id == winner and rec.effect_class == "read_only":
            if rec.target_resource in discarded_writes:
                if rec.pre_state_hash != discarded_writes[rec.target_resource]:
                    raise BranchContaminationError(
                        f"fork group {group.group_id}: winner {winner} read "
                        f"{rec.target_resource} at pre_state={rec.pre_state_hash} "
                        f"but discarded branch wrote post_state="
                        f"{discarded_writes[rec.target_resource]}; "
                        f"winner output is contaminated and must be re-executed "
                        f"from fork checkpoint"
                    )

def resume_from_checkpoint(group: ForkGroup, checkpoint_hash: str) -> None:
    if group.winner is None:
        raise BranchContaminationError(
            f"fork group {group.group_id}: cannot resume, arbitration never quiesced"
        )
    # Re-execution path: discard all speculative effects, replay from clean state.
    group.ledger.clear()
    group.winner = None
    group.discarded = []
