# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-withhold-its-attestation-when-a-byzantine-quorum-s-signed-result-contradicts-its-own-local-execution-trace.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-withhold-its-attestation-when-a-byzantine-quorum-s-signed-result-contradicts-its-own-local-execution-trace.warrant.json
# Markdown SHA-256:   8aed887a28107b8e929aba566c87f7220716cbcb424144f46e937be73bf3fb4e
# Code AST SHA-256:   8b56c6f164127f874f9876a7f4f4069e3e781d424b70d714157fbcf64691b54c
# Verified Classes:   AttestationPosture, ByzantineQuorumError, ExecutionTrace, AttestedBundle
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from enum import Enum


class AttestationPosture(Enum):
    COUNTERSIGN = "countersign"
    ABSTAIN_LIVENESS = "abstain_liveness"
    HALT_CONTRADICTION = "halt_contradiction"


class ByzantineQuorumError(RuntimeError):
    """Raised when a local trace contradicts a threshold-signed result.

    This is a SAFETY event, not a liveness event. It must halt the ring,
    not be silently coerced into an abstention.
    """
    pass


@dataclass(frozen=True)
class ExecutionTrace:
    task_id: str
    result_hash: str
    replayable: bool  # deterministic task OR trace replays to stable result


@dataclass(frozen=True)
class AttestedBundle:
    task_id: str
    result_hash: str
    signer_ids: tuple
    quorum_threshold: int


def _hash(payload: bytes) -> str:
    return hashlib.sha256(payload).hexdigest()


def evaluate_attestation(
    trace: ExecutionTrace | None,
    bundle: AttestedBundle,
) -> AttestationPosture:
    # Step 1: no complete trace -> clean liveness abstention.
    if trace is None or trace.task_id != bundle.task_id:
        return AttestationPosture.ABSTAIN_LIVENESS

    # Step 2: agreement -> countersign.
    if trace.result_hash == bundle.result_hash:
        return AttestationPosture.COUNTERSIGN

    # Step 3: disagreement but trace not stable -> liveness abstention, do not accuse.
    if not trace.replayable:
        return AttestationPosture.ABSTAIN_LIVENESS

    # Step 4: stable trace contradicts a valid quorum -> HALT. Do not abstain.
    if len(bundle.signer_ids) < bundle.quorum_threshold:
        # Bundle isn't even a valid quorum; treat as malformed, not Byzantine.
        return AttestationPosture.ABSTAIN_LIVENESS

    proof = {
        "task_id": trace.task_id,
        "local_result_hash": trace.result_hash,
        "attested_result_hash": bundle.result_hash,
        "signer_ids": bundle.signer_ids,
        "proof_digest": _hash(
            f"{trace.result_hash}:{bundle.result_hash}:{bundle.signer_ids}".encode()
        ),
    }
    raise ByzantineQuorumError(
        f"Local trace contradicts attested quorum for task {trace.task_id}: "
        f"local={trace.result_hash[:12]} attested={bundle.result_hash[:12]} "
        f"signers={bundle.signer_ids} proof={proof['proof_digest'][:12]}"
    )


# --- Regression: the observed failure must NOT reproduce. ---
trace_c = ExecutionTrace(task_id="t-42", result_hash="R_C", replayable=True)
bundle_q = AttestedBundle(
    task_id="t-42", result_hash="R_Q",
    signer_ids=("A", "B", "D", "E"), quorum_threshold=4,
)

try:
    evaluate_attestation(trace_c, bundle_q)
    raise AssertionError("invariant violated: contradiction was not escalated")
except ByzantineQuorumError as e:
    print(f"correctly halted: {e}")

# --- Nondeterministic divergence must abstain, not accuse. ---
trace_nd = ExecutionTrace(task_id="t-42", result_hash="R_X", replayable=False)
posture = evaluate_attestation(trace_nd, bundle_q)
assert posture is AttestationPosture.ABSTAIN_LIVENESS
print(f"nondeterministic divergence -> {posture.value} (no false accusation)")
