# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-commit-to-a-quorum-that-no-longer-exists-phantom-quorum-commitment-under-view-change-churn-in-byzantine-agent-consensus.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-commit-to-a-quorum-that-no-longer-exists-phantom-quorum-commitment-under-view-change-churn-in-byzantine-agent-consensus.warrant.json
# Markdown SHA-256:   893ee53e8bb814dde42e95924f8aa22a7b81bcaefb09c1d6095df530122f42a0
# Code AST SHA-256:   b5be28db5339dfad0c2cbf5a26d3f0d1f588ddf1e19f3118a0e821f93046ac8e
# Verified Classes:   StaleQuorumCertificateError, QuorumCertificate, AgentConsensusState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Dict, Set


class StaleQuorumCertificateError(RuntimeError):
    """Raised when a PREPARE certificate is executed after its signing epoch has closed."""
    pass


@dataclass
class QuorumCertificate:
    view: int
    value_hash: str
    signers: Set[str]
    collected_at: float = field(default_factory=time.monotonic)


@dataclass
class AgentConsensusState:
    agent_id: str
    current_view: int = 0
    observed_view_changes: Set[int] = field(default_factory=set)
    executed_certificates: Dict[int, str] = field(default_factory=dict)

    def observe_view_change(self, target_view: int) -> None:
        # Observation is a one-way door: once seen, the old epoch is closed.
        if target_view > self.current_view:
            self.observed_view_changes.add(target_view)

    def execute_commit(self, qc: QuorumCertificate, quorum_size: int) -> str:
        if len(qc.signers) < quorum_size:
            raise StaleQuorumCertificateError(
                f"certificate for view {qc.view} has {len(qc.signers)} signers, "
                f"below quorum {quorum_size}"
            )
        # Guard 1: certificate epoch must match the executor's live view.
        if qc.view < self.current_view:
            raise StaleQuorumCertificateError(
                f"certificate view {qc.view} is behind current view {self.current_view}"
            )
        # Guard 2: reject if a higher-view VIEW-CHANGE has been OBSERVED,
        # even if not yet applied. This is the phantom-quorum guard.
        higher = {v for v in self.observed_view_changes if v > qc.view}
        if higher:
            raise StaleQuorumCertificateError(
                f"certificate view {qc.view} is stale: observed view-change(s) "
                f"{sorted(higher)} signal epoch closure"
            )
        # Guard 3: idempotent execution per view.
        if qc.view in self.executed_certificates:
            return self.executed_certificates[qc.view]
        self.executed_certificates[qc.view] = qc.value_hash
        return qc.value_hash


# Reproduce the observed incident: A5 has observed a VIEW-CHANGE to v=5
# but has not yet applied it; A3's late v=4 COMMIT must be rejected.
a5 = AgentConsensusState(agent_id="A5", current_view=4)
a5.observe_view_change(5)  # pending, not applied

late_qc = QuorumCertificate(
    view=4, value_hash="H1", signers={"A1", "A2", "A3", "A5", "A6"}
)

try:
    a5.execute_commit(late_qc, quorum_size=5)
except StaleQuorumCertificateError as exc:
    print(f"REJECTED (correct): {exc}")
else:
    raise StaleQuorumCertificateError(
        "phantom quorum commitment: stale v=4 certificate executed after "
        "v=5 view-change was observed"
    )
