# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-verifier-gated-commit-has-already-been-poisoned-by-a-speculative-branch-it-pruned-for-cost-reasons.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-verifier-gated-commit-has-already-been-poisoned-by-a-speculative-branch-it-pruned-for-cost-reasons.warrant.json
# Markdown SHA-256:   3568ad1540c53b25cf48de4ac95dda2caa6f4a696cc57402eeae087ab0a57f0c
# Code AST SHA-256:   fa243dc636187e42252bfcb4f958013a826a78a4897d6313ac7b6d7b8fa85fdd
# Verified Classes:   CommitProvenanceError, WriteEvent
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CommitProvenanceError(RuntimeError):
    """Raised when committed state would include a write from a non-committed
    branch, or a write with no provenance tag at all."""
    pass


class WriteEvent:
    __slots__ = ("key", "value", "author_branch", "epoch")

    def __init__(self, key, value, author_branch, epoch):
        self.key = key
        self.value = value
        self.author_branch = author_branch  # None => untagged, fail closed
        self.epoch = epoch


def commit_state(write_log, committed_branches, current_epoch):
    """Project committed state through a provenance filter.

    write_log: iterable of WriteEvent, in append order.
    committed_branches: set of branch IDs that won the verifier gate.
    current_epoch: highest liveness epoch observed; writes from pruned
        branches bearing an epoch <= current_epoch are still filtered by
        branch membership, not by epoch alone.
    """
    committed = {}
    for ev in write_log:
        if ev.author_branch is None:
            raise CommitProvenanceError(
                f"untagged write to {ev.key!r} at epoch {ev.epoch}; "
                "refusing to admit unprovenanced state"
            )
        if ev.author_branch not in committed_branches:
            # Pruned-but-persisted branch: drop its effect silently at commit.
            continue
        if ev.epoch > current_epoch:
            raise CommitProvenanceError(
                f"write to {ev.key!r} from branch {ev.author_branch} "
                f"has future epoch {ev.epoch} > {current_epoch}; "
                "clock/epoch fencing violated"
            )
        committed[ev.key] = ev.value
    return committed


def commit_or_halt(write_log, committed_branches, current_epoch):
    try:
        return commit_state(write_log, committed_branches, current_epoch)
    except CommitProvenanceError as e:
        # Halt the commit; do not advance durable state with partial projection.
        raise CommitProvenanceError(
            f"commit aborted, state not advanced: {e}"
        ) from e
