# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-commit-under-partial-synchrony-the-silent-quorum-equivocation-boundary-in-bft-task-commitment.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-commit-under-partial-synchrony-the-silent-quorum-equivocation-boundary-in-bft-task-commitment.warrant.json
# Markdown SHA-256:   973cf0fde8763724105a884a6c5fef92779ec4a0f279c84a7cd3c99ba38085d7
# Code AST SHA-256:   bbd61fcc4a2e030a78134e08fc32ad3953bc2db6eed92b6cfcba7a28c10b7af1
# Verified Classes:   UnsafeCommitError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnsafeCommitError(RuntimeError):
    """Raised when a commit would be issued outside the quorum-validity condition."""
    pass


def commit_decision(
    height: int,
    view: int,
    value: str,
    votes: list[dict],          # each: {"replica_id", "height", "view", "value", "sig"}
    highest_known_view: int,
    f: int,
) -> str:
    threshold = 2 * f + 1

    if view != highest_known_view:
        raise UnsafeCommitError(
            f"stale view {view} != highest known {highest_known_view} at height {height}"
        )

    # Bind each signature to (height, view) and detect single-value-per-replica.
    signers_for_value: set[str] = set()
    values_by_replica: dict[str, set[str]] = {}
    for v in votes:
        if v["height"] != height or v["view"] != view:
            continue  # stale or mis-bound evidence never counts
        rid = v["replica_id"]
        values_by_replica.setdefault(rid, set()).add(v["value"])
        if v["value"] == value:
            signers_for_value.add(rid)

    equivocators = {rid for rid, vals in values_by_replica.items() if len(vals) > 1}
    if equivocators:
        # A replica that signed two values at this height is Byzantine; its
        # entire contribution is untrusted for this height.
        signers_for_value -= equivocators

    distinct = len(signers_for_value)
    if distinct < threshold:
        raise UnsafeCommitError(
            f"height {height} view {view}: only {distinct} distinct valid signers "
            f"for value {value!r} (need {threshold}); "
            f"raw vote count was {len(votes)} — inflation or equivocation detected"
        )

    return value
