# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-branch-is-unsound-before-committing-its-effects-the-read-set-provenance-invariant-in-parallel-branch-an.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-speculative-branch-is-unsound-before-committing-its-effects-the-read-set-provenance-invariant-in-parallel-branch-an.warrant.json
# Markdown SHA-256:   b47003d61a35511674540049a6ab2ea219aaa24e329e6577208ac89c01224c25
# Code AST SHA-256:   4f878dc68bcd677f443d5b2e722ed324ebe9f070b81cebc10c2458b502db3298
# Verified Classes:   ContaminatedCommitError, TraceEvent, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class ContaminatedCommitError(RuntimeError):
    """Raised when a speculative branch is about to commit effects whose
    justification depended on a read that overlapped a sibling's live write."""
    pass


@dataclass
class TraceEvent:
    kind: str          # "read" | "write"
    resource: str
    timestamp: float
    branch_id: str


@dataclass
class Branch:
    branch_id: str
    events: list[TraceEvent] = field(default_factory=list)
    revalidation_budget: int = 2
    committed: bool = False


def write_visibility_windows(branches: list[Branch]) -> dict[str, list[tuple[float, float, str]]]:
    """Map resource -> [(apply_time, close_time, branch_id)] for speculative writes.
    A window closes at commit/rollback; here we model it as still-open until selection."""
    windows: dict[str, list[tuple[float, float, str]]] = {}
    now = time.time()
    for b in branches:
        for e in b.events:
            if e.kind == "write":
                windows.setdefault(e.resource, []).append((e.timestamp, now, b.branch_id))
    return windows


def is_contaminated(branch: Branch, windows: dict[str, list[tuple[float, float, str]]]) -> Optional[TraceEvent]:
    """Return the first read event in `branch` that falls inside a *sibling's*
    write-visibility window on the same resource, else None."""
    for e in branch.events:
        if e.kind != "read":
            continue
        for (apply_t, close_t, writer) in windows.get(e.resource, []):
            if writer == branch.branch_id:
                continue
            if apply_t <= e.timestamp <= close_t:
                return e
    return None


def commit_branch(branch: Branch, siblings: list[Branch]) -> None:
    windows = write_visibility_windows(siblings)
    contamination = is_contaminated(branch, windows)
    if contamination is None:
        branch.committed = True
        return

    # Contaminated: attempt bounded re-validation.
    while branch.revalidation_budget > 0:
        branch.revalidation_budget -= 1
        # Re-read the contaminated resource; here we model re-read as clean
        # only if no sibling window now covers the new timestamp.
        retry_ts = time.time()
        still = any(
            apply_t <= retry_ts <= close_t and writer != branch.branch_id
            for (apply_t, close_t, writer) in windows.get(contamination.resource, [])
        )
        if not still:
            branch.committed = True
            return

    raise ContaminatedCommitError(
        f"branch {branch.branch_id} read {contamination.resource} at "
        f"t={contamination.timestamp:.3f} inside a sibling write-visibility window; "
        f"re-validation budget exhausted ({branch.revalidation_budget} left). "
        f"Branch is uncommittable and must be excluded from selection."
    )


def select_and_commit(branches: list[Branch], costs: dict[str, float]) -> Branch:
    """Select the cheapest branch, but force re-validation of the winner's
    read-set before the selection is finalized."""
    winner = min(branches, key=lambda b: costs[b.branch_id])
    others = [b for b in branches if b.branch_id != winner.branch_id]
    commit_branch(winner, siblings=others)
    if not winner.committed:
        raise ContaminatedCommitError(
            f"winner {winner.branch_id} failed post-selection re-validation; "
            f"selection must fall through to next-cheapest clean branch."
        )
    return winner
