# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abort-a-speculative-plan-branch-after-a-consensus-quorum-has-already-committed-to-it.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abort-a-speculative-plan-branch-after-a-consensus-quorum-has-already-committed-to-it.warrant.json
# Markdown SHA-256:   e23195dccc4e195a480b0171ee0144632e3329e242eafff160cf128859696de7
# Code AST SHA-256:   de460ad6c41b4d50963e9bdb2b2c2397248319017947a6d918cf96c28b380d49
# Verified Classes:   CommitmentPreconditionViolated, CommitLog
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CommitmentPreconditionViolated(RuntimeError):
    """Raised when an executor observes a precondition violation on a
    quorum-committed speculative branch and must abort locally without
    quorum re-vote."""
    def __init__(self, branch_id: str, precondition: str, observed: int, required: int, seq: int):
        self.branch_id = branch_id
        self.precondition = precondition
        self.observed = observed
        self.required = required
        self.seq = seq
        super().__init__(
            f"branch {branch_id} precondition {precondition} violated at seq={seq}: "
            f"observed={observed} required={required}"
        )


class CommitLog:
    def __init__(self):
        self._entries = []  # append-only, per-branch total order enforced on read
        self._aborted = {}  # branch_id -> seq of first ABORT_OBSERVED

    def append_abort(self, branch_id: str, seq: int, signer: str):
        # unilateral: single signer, no quorum required
        self._entries.append({"type": "ABORT_OBSERVED", "branch_id": branch_id,
                              "seq": seq, "signer": signer})
        self._aborted.setdefault(branch_id, seq)

    def is_aborted(self, branch_id: str, consumed_seq: int) -> bool:
        abort_seq = self._aborted.get(branch_id)
        return abort_seq is not None and abort_seq > consumed_seq


def execute_step(
    branch_id: str,
    step_idx: int,
    precondition: str,
    required: int,
    observe,
    log: CommitLog,
    consumed_seq: int,
) -> int:
    # Boundary check 1: has an abort record appeared past our consumed seq?
    if log.is_aborted(branch_id, consumed_seq):
        raise CommitmentPreconditionViolated(
            branch_id, precondition, -1, required, consumed_seq
        )
    # Boundary check 2: re-check precondition from our own observation channel
    observed = observe(precondition)
    if observed < required:
        # Unilateral abort: append and raise. No quorum re-vote.
        log.append_abort(branch_id, seq=consumed_seq + 1, signer="executor_local")
        raise CommitmentPreconditionViolated(
            branch_id, precondition, observed, required, consumed_seq + 1
        )
    return observed


def run_branch(branch_id, steps, observe, log, start_seq):
    seq = start_seq
    for idx, (pre, req) in enumerate(steps):
        try:
            run_step_observe = execute_step(branch_id, idx, pre, req, observe, log, seq)
            seq += 1
        except CommitmentPreconditionViolated:
            # Branch is dead; do not emit success record.
            return {"branch_id": branch_id, "status": "aborted", "at_step": idx}
    return {"branch_id": branch_id, "status": "completed", "seq_end": seq}
