# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-survive-speculative-branch-rollback-contamination-when-parallel-agent-forks-share-a-mutable-tool-effect-log.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-survive-speculative-branch-rollback-contamination-when-parallel-agent-forks-share-a-mutable-tool-effect-log.warrant.json
# Markdown SHA-256:   93b9cedc9704d6843f6aa6942efd79a7fc5155a124a455609355c39b360f4eb0
# Code AST SHA-256:   e4ab2eb06d776504312cae6af1547a4f99c32dde0aab8891b8696135a674ce4e
# Verified Classes:   BranchContaminationError, Effect, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class BranchContaminationError(RuntimeError):
    """Raised when a speculative winner's read-set intersects a loser's write-set
    on a surface that admits no compensating inverse or branch isolation."""


@dataclass(frozen=True)
class Effect:
    surface: str          # e.g. "staging_db", "outbound_email", "rate_counter"
    key: str              # row id, recipient, counter name; "" means unkeyed/whole-surface
    op: str               # "read" | "write"
    seq: int              # monotonic per-branch ordering
    invertible: bool      # False for email sends, charges, monotonic increments


@dataclass
class Branch:
    name: str
    effects: list[Effect] = field(default_factory=list)
    succeeded: bool = False


def _intersects(loser: Branch, winner: Branch) -> list[tuple[Effect, Effect]]:
    hits = []
    for w in winner.effects:
        if w.op != "read":
            continue
        for l in loser.effects:
            if l.op != "write":
                continue
            if l.surface != w.surface:
                continue
            # unkeyed read or unkeyed write means whole-surface contamination
            key_match = (not w.key) or (not l.key) or (w.key == l.key)
            if key_match and l.seq < w.seq:
                hits.append((l, w))
    return hits


def audit_merge(winner: Branch, losers: Iterable[Branch]) -> None:
    """Enforce the merge invariant: winner's success must be attributable to
    the winner alone. Re-observe the world; do not trust branch self-reports."""
    for loser in losers:
        hits = _intersects(loser, winner)
        if not hits:
            continue
        # A failed loser is MORE dangerous: its writes were never validated.
        severity = "failed-loser" if not loser.succeeded else "succeeded-loser"
        non_invertible = [l for (l, _) in hits if not l.invertible]
        if non_invertible:
            raise BranchContaminationError(
                f"winner={winner.name!r} contaminated by {severity} "
                f"branch={loser.name!r} on non-invertible surface(s) "
                f"{[e.surface for e in non_invertible]}; no rollback path, "
                f"abort and escalate to supervisor"
            )
        # Invertible but still contaminating: must re-run, not promote.
        raise BranchContaminationError(
            f"winner={winner.name!r} read-set intersects {severity} "
            f"branch={loser.name!r} write-set on invertible surface(s) "
            f"{[l.surface for (l, _) in hits]}; re-run winner against "
            f"re-observed world before promotion"
        )
    # No intersection: safe to promote winner's branch-private effects atomically.
