# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abort-a-speculative-fan-out-before-its-rollback-barrier-and-why-the-barrier-itself-is-the-failure-surface.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abort-a-speculative-fan-out-before-its-rollback-barrier-and-why-the-barrier-itself-is-the-failure-surface.warrant.json
# Markdown SHA-256:   0355a2c2c79c4e7060f79d732afdbc87d88eef0a805274081a11fc611485d889
# Code AST SHA-256:   0af6617d3cf6ea2cbef81b54d0d98c65fbc455a4008a667ef7312c93e910f1b6
# Verified Classes:   SpeculativeRollbackViolation, Branch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SpeculativeRollbackViolation(RuntimeError):
    """Raised when a speculative branch leaks an effect past the rollback barrier."""
    pass


class Branch:
    def __init__(self, branch_id, declared_effects, depends_on=()):
        self.branch_id = branch_id
        self.declared_effects = set(declared_effects)   # effects the branch promises
        self.runtime_effects = set()                     # effects actually observed
        self.depends_on = set(depends_on)                # sibling branch_ids consumed
        self.status = "staged"


def admit_to_fanout(branch, buffer_surface, sibling_ids):
    # Condition 1 & 2: effects must be confined to the staging buffer.
    leaked = branch.declared_effects - buffer_surface
    if leaked:
        raise SpeculativeRollbackViolation(
            f"branch {branch.branch_id} declares non-buffer effects {leaked}; "
            f"not admissible to speculative fan-out"
        )
    # Condition 3: no dependency on a sibling's provisional output.
    bad_deps = branch.depends_on & sibling_ids
    if bad_deps:
        raise SpeculativeRollbackViolation(
            f"branch {branch.branch_id} depends on provisional siblings {bad_deps}; "
            f"must run post-barrier"
        )
    return True


def evaluate_barrier(branches, buffer_surface):
    for b in branches:
        # Re-check at barrier time: did runtime effects exceed the declared set?
        escaped = b.runtime_effects - b.declared_effects
        if escaped:
            raise SpeculativeRollbackViolation(
                f"branch {b.branch_id} leaked effects {escaped} past the stage "
                f"boundary; rollback is inadmissible, invoke compensators"
            )
    diverged = any(b.status == "diverged" for b in branches)
    if diverged:
        for b in branches:
            b.status = "rolled_back"   # safe: all effects still staged
        return "ABORTED_CLEAN"
    for b in branches:
        b.status = "committed"
    return "COMMITTED"
