# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-speculative-branch-contamination-when-a-losing-draft-s-tool-side-effects-survive-rollback-and-poison-the-winner-s-verifica.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-speculative-branch-contamination-when-a-losing-draft-s-tool-side-effects-survive-rollback-and-poison-the-winner-s-verifica.warrant.json
# Markdown SHA-256:   e69016e34b48e910b11febc5ac3f341b3c9d499d6d52cf4932b96a73198d99a1
# Code AST SHA-256:   7c04decb618cec8191ee372c04ad8a4bd23341dd2ebec920108db5f6ed851c08
# Verified Classes:   SpeculativeContaminationError, BranchWrite, Branch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class SpeculativeContaminationError(RuntimeError):
    """Raised when a winning branch's verification substrate was mutated by a losing sibling."""


@dataclass
class BranchWrite:
    resource_id: str
    fingerprint: str  # e.g. sha256 of content the branch believes it wrote


@dataclass
class Branch:
    branch_id: str
    writes: list[BranchWrite] = field(default_factory=list)
    committed: bool = False


def read_live_fingerprint(resource_id: str, substrate: dict[str, bytes]) -> str:
    return hashlib.sha256(substrate[resource_id]).hexdigest()


def select_winner_and_assert_clean(
    winner: Branch,
    losers: list[Branch],
    substrate: dict[str, bytes],
) -> None:
    """Barrier check: the winner's expected post-state must match live state.

    Runs after rollback of losers' *state* but before the winner's verification
    replay. Detects sibling contamination of shared external resources.
    """
    if not winner.committed:
        raise SpeculativeContaminationError(
            f"winner {winner.branch_id} selected before commit; barrier violated"
        )

    for write in winner.writes:
        if write.resource_id not in substrate:
            raise SpeculativeContaminationError(
                f"winner {winner.branch_id} wrote {write.resource_id} but resource is absent"
            )
        live = read_live_fingerprint(write.resource_id, substrate)
        if live != write.fingerprint:
            # Identify which sibling likely contaminated the substrate.
            suspects = [
                b.branch_id
                for b in losers
                if any(w.resource_id == write.resource_id for w in b.writes)
            ]
            raise SpeculativeContaminationError(
                f"post-state divergence on {write.resource_id}: "
                f"winner expected {write.fingerprint[:12]}, live {live[:12]}; "
                f"losing branches that touched this resource: {suspects}. "
                f"Winner verification replay is invalid; re-draft from fresh checkpoint."
            )
