# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-attest-a-peer-s-result-the-quorum-intersection-illusion-in-byzantine-multi-agent-commitment.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-attest-a-peer-s-result-the-quorum-intersection-illusion-in-byzantine-multi-agent-commitment.warrant.json
# Markdown SHA-256:   4510f3d207e0e977b248b0e8d806a725859cdb94a7bbec84614e10eb56e767ec
# Code AST SHA-256:   efbea52966145e91f0afb7276c0fe7fc3a393bcc5445700de4fcd0fd37a9fb9c
# Verified Classes:   AttestationRefused, Value, AttestationRequest, AttestationLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class AttestationRefused(RuntimeError):
    """Raised when an instance must abstain rather than emit a quorum-countable attestation."""
    pass


class Value(Enum):
    PASS = "PASS"
    FAIL = "FAIL"
    UNDECIDED = "UNDECIDED"


@dataclass(frozen=True)
class AttestationRequest:
    epoch: int
    task_id: str
    requester_result_leaked: bool   # requester's claimed result present in context
    peers_results_leaked: bool      # any peer result present in context
    batched_with_others: bool       # merged into a shared context window
    evidence_marginal: bool         # own execution landed in the uncertainty band


class AttestationLedger:
    """Signed, append-only, keyed by (epoch, task_id, agent_id). Serves replays."""

    def __init__(self) -> None:
        self._log: dict[tuple[int, str, str], Value] = {}

    def committed(self, epoch: int, task_id: str, agent_id: str) -> Value | None:
        return self._log.get((epoch, task_id, agent_id))

    def commit(self, epoch: int, task_id: str, agent_id: str, value: Value) -> None:
        self._log[(epoch, task_id, agent_id)] = value


def attest(
    agent_id: str,
    req: AttestationRequest,
    own_sample: Value,
    ledger: AttestationLedger,
) -> Value:
    # Idempotent replay: never re-derive a second sample in the same epoch.
    prior = ledger.committed(req.epoch, req.task_id, agent_id)
    if prior is not None:
        return prior

    # Tripwire 1 & 2: contaminated context -> the sample is not a stable witness.
    if req.requester_result_leaked or req.peers_results_leaked:
        raise AttestationRefused(
            f"agent {agent_id}: attestation context leaks requester/peer results; "
            f"sample is auditor-conditioned and cannot enter the quorum count"
        )

    # Tripwire 3: batching collapses independent samples into a false consistency.
    if req.batched_with_others:
        raise AttestationRefused(
            f"agent {agent_id}: batched attestation request; "
            f"process as independent blinded samples or refuse"
        )

    # Tripwire 4: marginal evidence is the node that flips under conditioning.
    if req.evidence_marginal:
        ledger.commit(req.epoch, req.task_id, agent_id, Value.UNDECIDED)
        return Value.UNDECIDED

    ledger.commit(req.epoch, req.task_id, agent_id, own_sample)
    return own_sample


def commit_result(
    epoch: int,
    task_id: str,
    attestations: dict[str, Value],
    n: int,
    f: int,
) -> Value:
    quorum = (n + f + 1) // 2  # ceil((N+f+1)/2) for N >= 3f+1
    countable = {a: v for a, v in attestations.items() if v is not Value.UNDECIDED}
    passes = sum(1 for v in countable.values() if v is Value.PASS)
    fails = sum(1 for v in countable.values() if v is Value.FAIL)

    if passes >= quorum and fails >= quorum:
        # Should be unreachable under the determinism condition; if reached,
        # the intersection witness was a flip-flopper, not a stable testimony.
        raise AttestationRefused(
            f"epoch {epoch} task {task_id}: two quorums attested contradictory "
            f"results; quorum intersection held but testimony was unstable"
        )
    if passes >= quorum:
        return Value.PASS
    if fails >= quorum:
        return Value.FAIL
    return Value.UNDECIDED  # escalate to more agents or a deterministic oracle
