# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-commits-to-a-task-without-quorum-verified-shared-state-in-bft-multi-agent-consensus.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-commits-to-a-task-without-quorum-verified-shared-state-in-bft-multi-agent-consensus.warrant.json
# Markdown SHA-256:   9ca608cdff4bbcca1312e8d4bd16c30993a39e845775a28d3f8f305be8a89374
# Code AST SHA-256:   1bba1954fa459da21316213ecd6fa41eb7b826cb80c7ccfd92a3ac1091c24de3
# Verified Classes:   UncertifiedCommitmentError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class UncertifiedCommitmentError(RuntimeError):
    """Raised when an agent attempts to commit to a task without a quorum certificate."""
    pass


QUORUM_FRACTION_NUM = 2
QUORUM_FRACTION_DEN = 3


def required_quorum(n: int) -> int:
    # BFT threshold: 2f+1 where f = (n-1)//3
    f = (n - 1) // 3
    return 2 * f + 1


def commit_task(task_id: str, state_root: str, signed_votes: list[tuple[str, str]], n: int) -> bool:
    """
    signed_votes: list of (agent_id, signed_state_root) for this state_root.
    Commit only if matching votes reach the 2f+1 quorum for n agents.
    """
    matching = [v for v in signed_votes if v[1] == state_root]
    threshold = required_quorum(n)

    if len(matching) < threshold:
        raise UncertifiedCommitmentError(
            f"task={task_id} state_root={state_root} "
            f"votes={len(matching)} required={threshold} (n={n})"
        )

    # Safe to commit: quorum certificate verified for this exact state root.
    return True


def speculative_execute(task_id: str, state_root: str, signed_votes, n):
    try:
        commit_task(task_id, state_root, signed_votes, n)
        return "committed"
    except UncertifiedCommitmentError:
        # Do NOT execute irreversible work; mark speculative and re-vote.
        return "speculative_discard"
