# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-speculative-branch-divergence-when-parallel-planner-agents-disagree-on-a-shared-mutation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-speculative-branch-divergence-when-parallel-planner-agents-disagree-on-a-shared-mutation.warrant.json
# Markdown SHA-256:   8ceba47070d3f7c137aef2babe011cd51977857f63381b4f065d478cca737409
# Code AST SHA-256:   26f38a61610a589cd8b6a644e3fea7cf219f47e9562a31b3a15b0335852d14b2
# Verified Classes:   SpeculativeBranchContamination, Effect, Branch
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal


class SpeculativeBranchContamination(RuntimeError):
    """Raised when a speculative fan-out cannot be safely scored because at
    least one branch has already mutated a resource that another branch read
    or wrote, violating commit-time exclusivity of side effects."""


@dataclass
class Effect:
    branch_id: str
    resource: str
    kind: Literal["read", "write"]
    seq: int          # monotonic within branch
    staged: bool      # True if buffered, False if already applied live


@dataclass
class Branch:
    branch_id: str
    effects: list[Effect] = field(default_factory=list)


def detect_contamination(branches: list[Branch]) -> list[tuple[str, str, str]]:
    """Return (victim_branch, offender_branch, resource) for every pair where
    the victim's read post-dates the offender's write on the same resource,
    or where any branch has an unstaged write."""
    violations: list[tuple[str, str, str]] = []

    for b in branches:
        for e in b.effects:
            if e.kind == "write" and not e.staged:
                violations.append((b.branch_id, b.branch_id, e.resource))

    for victim in branches:
        for offender in branches:
            if victim.branch_id == offender.branch_id:
                continue
            for r in victim.effects:
                if r.kind != "read":
                    continue
                for w in offender.effects:
                    if w.kind == "write" and w.resource == r.resource and w.seq < r.seq:
                        violations.append((victim.branch_id, offender.branch_id, r.resource))
    return violations


def commit_branch(branches: list[Branch], winner_id: str) -> str:
    violations = detect_contamination(branches)
    if violations:
        detail = "; ".join(
            f"{v} read/wrote {res} after {o} mutated it" for v, o, res in violations
        )
        raise SpeculativeBranchContamination(
            f"fan-out void: cannot score branches, {len(violations)} contamination(s): {detail}. "
            f"Re-derive from a common snapshot or refuse the fan-out."
        )
    winner = next(b for b in branches if b.branch_id == winner_id)
    # Only now is it safe to promote the winner's staged effects to live.
    return winner_id
