# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-treat-an-llm-agent-s-vote-as-a-signed-commitment-rather-than-an-opinion-equivocating-agents-and-the-quorum-forgery-boundary-in.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-treat-an-llm-agent-s-vote-as-a-signed-commitment-rather-than-an-opinion-equivocating-agents-and-the-quorum-forgery-boundary-in.warrant.json
# Markdown SHA-256:   386a486a651c6de4825fe1d45ef804e4cab53c79f304b27a6045c51448e41ec3
# Code AST SHA-256:   3561a7725de24f7a4a51b37503bbeb26bba0194713b68d028576cf9cd343cd6c
# Verified Classes:   VoteLedgerViolation, VoteLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class VoteLedgerViolation(RuntimeError):
    """Raised when an LLM replica would emit a second, conflicting vote
    for an already-committed (height, view), orphaning the quorum-intersection
    safety proof of the BFT protocol."""
    pass


class VoteLedger:
    """Durable, unique-per-(instance,height,view) commitment store.
    The model is invoked at most once per key; all retries read through."""

    def __init__(self, instance_id: str):
        self.instance_id = instance_id
        self._store: dict[tuple[int, int], dict] = {}

    def commit_vote(self, height: int, view: int, plan_hash: str,
                    decision: str, sign_fn) -> dict:
        key = (height, view)
        existing = self._store.get(key)
        if existing is not None:
            # Retry path: never re-invoke the model, never re-sign.
            if existing["plan_hash"] != plan_hash or existing["decision"] != decision:
                raise VoteLedgerViolation(
                    f"instance {self.instance_id} already committed "
                    f"{existing['decision']} for h={height} v={view}; "
                    f"refusing conflicting {decision} (equivocation by amnesia)"
                )
            return existing  # idempotent re-send of stored bytes
        record = {
            "instance_id": self.instance_id,
            "height": height,
            "view": view,
            "plan_hash": plan_hash,
            "decision": decision,
            "signature": sign_fn((height, view, plan_hash, decision)),
        }
        self._store[key] = record  # persist BEFORE gossip
        return record

    def emit(self, height: int, view: int, plan_hash: str, decision: str,
             sign_fn, gossip_fn) -> None:
        record = self.commit_vote(height, view, plan_hash, decision, sign_fn)
        try:
            gossip_fn(record)
        except TimeoutError:
            # Transport retry: re-send stored bytes, do NOT call the model.
            gossip_fn(record)


def handle_proposal_retry(ledger: VoteLedger, height: int, view: int,
                          plan_hash: str, prompt_bytes: str,
                          original_prompt_bytes: str, decide_fn, sign_fn,
                          gossip_fn) -> None:
    if (height, view) in ledger._store:
        # Already voted: replay stored vote regardless of new prompt bytes.
        stored = ledger._store[(height, view)]
        gossip_fn(stored)
        return
    if prompt_bytes != original_prompt_bytes:
        # Context compaction mutated the input: this is a NEW proposal,
        # not a retry. Reusing (height, view) would be quorum forgery.
        raise VoteLedgerViolation(
            f"prompt bytes changed for h={height} v={view}; "
            f"must escalate to a new view, not re-reason at same slot"
        )
    decision = decide_fn(prompt_bytes)
    ledger.emit(height, view, plan_hash, decision, sign_fn, gossip_fn)
