# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-speculative-branch-execution-before-the-commit-barrier-and-how-does-the-rollback-ledger-preserve-causalit.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-speculative-branch-execution-before-the-commit-barrier-and-how-does-the-rollback-ledger-preserve-causalit.warrant.json
# Markdown SHA-256:   e509a2256d649b3b6db5c784648526c0b325b03e2d7a0bd206741da9b7a42b3b
# Code AST SHA-256:   e6b4ee8c7905857694af2f915ff9fe41991ebb2507f13675c14ad49f7d85266c
# Verified Classes:   SpeculativeEpoch, PhantomDependencyError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set

@dataclass
class SpeculativeEpoch:
    # branch_id -> set of (resource, version) it wrote speculatively
    write_sets: Dict[str, Set[tuple]] = field(default_factory=dict)
    # branch_id -> set of (resource, version) its decisions consumed
    read_sets: Dict[str, Set[tuple]] = field(default_factory=dict)
    rolled_back: Set[str] = field(default_factory=set)

class PhantomDependencyError(RuntimeError):
    """A surviving branch consumed a speculative write from a rolled-back sibling."""

def commit_barrier(epoch: SpeculativeEpoch, survivors: Set[str]) -> Set[str]:
    """Return the set of branches safe to commit, or raise if any survivor
    read a version produced by a rolled-back branch."""
    retracted: Set[tuple] = set()
    for b in epoch.rolled_back:
        retracted |= epoch.write_sets.get(b, set())

    for s in survivors:
        consumed = epoch.read_sets.get(s, set())
        overlap = consumed & retracted
        if overlap:
            # Causal isolation invariant violated: survivor's decision is
            # grounded in a fact that was retracted. Abort the epoch.
            raise PhantomDependencyError(
                f"branch {s} read retracted speculative state {sorted(overlap)}; "
                f"commit barrier must abort epoch and replay from last durable checkpoint"
            )
    return set(survivors)

def run_epoch(epoch: SpeculativeEpoch, survivors: Set[str]) -> Set[str]:
    try:
        return commit_barrier(epoch, survivors)
    except PhantomDependencyError as e:
        # Default policy: full-epoch abort, not partial commit.
        epoch.rolled_back |= survivors
        raise PhantomDependencyError(
            f"epoch aborted after phantom dependency: {e}"
        ) from e
