# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-withhold-its-own-vote-to-preserve-byzantine-fault-tolerant-plan-commitment-when-the-quorum-threshold-is-computed-ov.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-withhold-its-own-vote-to-preserve-byzantine-fault-tolerant-plan-commitment-when-the-quorum-threshold-is-computed-ov.warrant.json
# Markdown SHA-256:   aad1cf7592a5df97b95e9c58ec0a93d4433e0856ad1bc0ba69a5fd2385366bb5
# Code AST SHA-256:   d392658b55f60ffa2f75f924ac9765dca66a9c0a1d8e96ee2d5a67af7553d79a
# Verified Classes:   RosterDriftPivotError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class RosterDriftPivotError(RuntimeError):
    """Raised when casting a vote would make this agent pivotal under a
    roster snapshot that differs from the proposal's pinned snapshot,
    collapsing the f+1 intersection guarantee."""
    pass


def cast_vote(agent_id, plan, local_roster, tally, proposal_roster_digest):
    # Q is pinned to the proposal's roster, never recomputed from local_roster.
    proposal_n = plan.roster_size
    f = (proposal_n - 1) // 3
    q_p = 2 * f + 1

    local_digest = local_roster.digest()
    drifted = local_digest != proposal_roster_digest

    # Vote would be pivotal iff tally is exactly one short of the pinned quorum.
    pivotal = (tally == q_p - 1)

    if drifted and pivotal:
        # Abstain: this vote would be the deciding vote for two universes.
        raise RosterDriftPivotError(
            f"agent {agent_id} refusing pivotal vote on plan {plan.id}: "
            f"local roster {local_digest} != proposal roster "
            f"{proposal_roster_digest}, tally={tally}, Q_P={q_p}. "
            f"Intersection with prior quorum would be < f+1={f + 1}."
        )

    if drifted and not pivotal:
        # Non-pivotal witness vote: cannot create a second decisive quorum.
        return {"vote": "witness", "plan": plan.id, "digest": local_digest}

    # Roster matches: normal vote.
    return {"vote": "commit", "plan": plan.id, "digest": local_digest}
