# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-its-rollback-anchor-when-speculative-branches-share-a-mutable-tool-effect-log.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-its-rollback-anchor-when-speculative-branches-share-a-mutable-tool-effect-log.warrant.json
# Markdown SHA-256:   7a04f1c5f0a905602753cac787362439cb5950d159a34f28c571935e34e4c73a
# Code AST SHA-256:   19a71d7303531172b86f34a8325ba9311a8ef282d14e0addf60a6dadeda78f3c
# Verified Classes:   RollbackAnchorViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class RollbackAnchorViolation(RuntimeError):
    """Raised when a speculative branch's rollback anchor was advanced by a sibling commit."""


def rollback_branch(log, branch, anchor_seq):
    # Effects authored by *this* branch between the anchor and now.
    own = [e for e in log.entries_after(anchor_seq) if e.branch_id == branch.id]
    foreign = [e for e in log.entries_after(anchor_seq) if e.branch_id != branch.id]

    if foreign:
        # A sibling's effect interleaved between our anchor and our writes.
        # An unconditional inverse would be misordered relative to its forward
        # effect and could clobber the sibling's committed state.
        raise RollbackAnchorViolation(
            f"branch {branch.id} anchor {anchor_seq} contaminated by "
            f"{len(foreign)} sibling effect(s) at seq "
            f"{[e.seq for e in foreign]}; unconditional inverse unsound"
        )

    for e in reversed(own):
        if not e.is_invertible():
            raise RollbackAnchorViolation(
                f"effect {e.seq} on branch {branch.id} is entangled (non-invertible); "
                f"branch must be serialized, not speculatively rolled back"
            )
        log.append(e.inverse())
    return log.head()


def consume_auditor_verdict(verdict, current_head):
    if verdict.observed_head != current_head:
        raise RollbackAnchorViolation(
            f"auditor verdict pinned to head {verdict.observed_head} but log is at "
            f"{current_head}; verdict is use-after-invalidation"
        )
    return verdict
