# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-agent-branch-has-crossed-the-commit-horizon-and-can-no-longer-be-rolled-back-safely.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-agent-branch-has-crossed-the-commit-horizon-and-can-no-longer-be-rolled-back-safely.warrant.json
# Markdown SHA-256:   91e4666ad751d640eb1d54622eaa8526db18249a00bcd576d8fd7fdd646890e2
# Code AST SHA-256:   310f31c420a90922930feb9a4bb0310b0a8dd0abe71df4cc6ad4ed12a30adc59
# Verified Classes:   CommitHorizonViolation, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CommitHorizonViolation(RuntimeError):
    """Raised when rollback is attempted on a branch whose effects have been
    acknowledged by an agent outside the branch's rollback domain."""
    pass


class Branch:
    def __init__(self, branch_id, rollback_domain):
        self.branch_id = branch_id
        self.rollback_domain = rollback_domain  # set of agent ids inside the domain
        self.effects = []          # emitted effects
        self.acknowledgments = []  # (effect_id, acknowledging_agent_id)
        self.descendants = []

    def acknowledgment_frontier(self):
        # Effects read-and-acted-on by an agent OUTSIDE the rollback domain.
        return [
            (eid, agent)
            for (eid, agent) in self.acknowledgments
            if agent not in self.rollback_domain
        ]

    def is_rollback_safe(self):
        return (
            not self.acknowledgment_frontier()
            and not self.descendants
        )


def rollback(scheduler, branch):
    frontier = branch.acknowledgment_frontier()
    if frontier:
        # Past the commit horizon: erasure would split canonical memory
        # from live agent context. Must compensate, not erase.
        raise CommitHorizonViolation(
            f"branch {branch.branch_id} has {len(frontier)} foreign "
            f"acknowledgment(s) {frontier}; rollback would corrupt state. "
            f"Route to compensation path."
        )
    if branch.descendants:
        raise CommitHorizonViolation(
            f"branch {branch.branch_id} spawned descendants "
            f"{[d.branch_id for d in branch.descendants]}; cascade or "
            f"quarantine before rollback."
        )
    # Safe: restore snapshot, drop branch-local effects.
    scheduler.restore_snapshot(branch)
    branch.effects.clear()
    return "rolled_back"
