# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-speculative-tool-call-execution-when-optimistic-concurrency-collides-with-byzantine-commit-quorum.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-speculative-tool-call-execution-when-optimistic-concurrency-collides-with-byzantine-commit-quorum.warrant.json
# Markdown SHA-256:   5d54f5263f6865d95daa4843e9e75d487fe82302465e3af200988d4cc59b0b8f
# Code AST SHA-256:   9d6431c5fe7d1aca6705ce60c8cb06d04b89d79ff2630cf23450373e057e6d87
# Verified Classes:   StaleWarrantCommitError, VoteDeduplicationError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class StaleWarrantCommitError(RuntimeError):
    """Raised when a Byzantine quorum would commit a speculative result
    whose warrant is older than the freshest version observed in-round."""
    pass


class VoteDeduplicationError(RuntimeError):
    """Raised when vote identity disjointness is violated (multiset quorum)."""
    pass


def commit_speculative_result(
    proposal,
    votes,
    fresh_versions,
    honest_set,
    f,
    fence_token,
):
    # 1. Fence token must be present for any side-effecting speculation.
    if proposal.side_effecting and fence_token is None:
        raise StaleWarrantCommitError(
            f"side-effecting speculation {proposal.call_id} issued without fence token; "
            "compensate the effect before re-proposing"
        )

    # 2. Identity-based deduplication, not role-label deduplication.
    seen = set()
    deduped = []
    for v in votes:
        key = v.cryptographic_identity
        if key in seen:
            raise VoteDeduplicationError(
                f"duplicate vote identity {key} in round {proposal.round_id}; "
                "role-label dedup would have masked this as distinct voters"
            )
        seen.add(key)
        deduped.append(v)

    accepts = [v for v in deduped if v.accept]
    max_fresh = max(fresh_versions.values()) if fresh_versions else proposal.read_version

    # 3. Stale-warrant check: every accept must be against a version >= proposal read,
    #    and the proposal's read must not be behind the freshest in-round observation.
    if proposal.read_version < max_fresh:
        raise StaleWarrantCommitError(
            f"proposal read_version={proposal.read_version} < freshest observed "
            f"{max_fresh}; speculative result is contaminated, abort and recompute"
        )
    for v in accepts:
        if v.warrant_version < proposal.read_version:
            raise StaleWarrantCommitError(
                f"voter {v.cryptographic_identity} accepted against warrant_version="
                f"{v.warrant_version} < proposal read_version={proposal.read_version}"
            )

    # 4. Quorum intersection with honest set after deduplication.
    honest_accepts = [v for v in accepts if v.cryptographic_identity in honest_set]
    if len(accepts) < 2 * f + 1 or len(honest_accepts) < f + 1:
        raise StaleWarrantCommitError(
            f"quorum insufficient after dedup: accepts={len(accepts)} "
            f"(need {2*f+1}), honest_accepts={len(honest_accepts)} (need {f+1})"
        )

    return proposal.result
